Another good way to serialize an object to String is to convert it to JSON or XML representation. One great advantage of this approach is that the Java class does not need to implement theSerializableinterface. This is specially useful if the class is part of legacy source code and a 3rd-...
importjava.io.*;classEmployeeimplementsSerializable{privateStringname;privatetransientintage;// transient关键字标识该属性不会被序列化publicEmployee(Stringname,intage){this.name=name;this.age=age;}// Getter和SetterpublicStringgetName(){returnname;}publicintgetAge(){returnage;}}publicclassSerializeDemo{pub...
ObjectOutputStream objectOutputStream; objectOutputStream=newObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(obj); String string= byteArrayOutputStream.toString("ISO-8859-1"); objectOutputStream.close(); byteArrayOutputStream.close();returnstring; }publicstaticObject serializeToObj...
";try{ByteArrayOutputStreambaos=newByteArrayOutputStream();ObjectOutputStreamoos=newObjectOutputStream(baos);oos.writeObject(str);byte[]bytes=baos.toByteArray();// 将字节数组转换为字符串StringserializedString=newString(bytes);System.out.println("Serialized String: "+serializedString);}catch(IOException...
packer.write(new String[]{"msg", "pack", "for", "java"}); packer.write(new byte[]{0x30, 0x31, 0x32}); // byte array // Serialize various types of other reference values packer.write("MessagePack"); // String object packer.write(ByteBuffer.wrap(new byte[]{0x30, 0x31, 0x32}...
import java.io.*;publicclassSerializeDemo {publicstaticvoidmain(String[] args) { Employee e=newEmployee(); e.name="LittleHann"; e.address="Hangzhou"; e.SSN=23333; e.number=101;try{ String savePath="C:/employee.ser"; FileOutputStream fileOut=newFileOutputStream(savePath); ...
public class SerializeTool { public static String object2String(Object obj) { String objBody = null; ByteArrayOutputStream baops = null; ObjectOutputStream oos = null; try { baops = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baops); ...
publicstaticStringserialize(Serializableobj)throwsException{if(obj!=null){ByteArrayOutputStreambos=null;ObjectOutputStreamoos=null;try{bos=newByteArrayOutputStream();oos=newObjectOutputStream(bos);oos.writeObject(obj);byte[]bytes=bos.toByteArray();returnbytesToString(bytes);}catch(Exceptione){e.print...
Object obj = ois.readObject(); ois.close(); return obj; } // serialize the given object and save it to file public static void serialize(Object obj, String fileName) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); ...
SerializeDemo.java 文件代码: importjava.io.*;publicclassSerializeDemo{publicstaticvoidmain(String[]args){Employeee=newEmployee();e.name="Reyan Ali";e.address="Phokka Kuan, Ambehta Peer";e.SSN=11122333;e.number=101;try{FileOutputStreamfileOut=newFileOutputStream("/tmp/employee.ser");ObjectOut...