1. Java对象序列化的基本用法 在Java中,我们可以使用ObjectOutputStream类将对象序列化为字节流,使用ObjectInputStream类将字节流反序列化为对象。下面是一个简单的示例: importjava.io.*;publicclassSerializationExample{publicstaticvoidmain(String[]args){try{// Serialize objectFileOutputStreamfileOut=newFileOutput...
private static void serializePerson(Person person) throws IOException { File file=new File("F:\\Person.txt"); if(!file.isFile()){ file.createNewFile(); } FileOutputStream fos=new FileOutputStream(file); ObjectOutputStream oos=new ObjectOutputStream(fos);//使用oos将Person对象写进F盘中的Pers...
public static void serialize(String fileName){ try { ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(fileName)); out.writeObject("序列化的日期是:");//序列化一个字符串到文件 out.writeObject(new Date());//序列化一个当前日期对象到文件 UserInfo userInfo=new UserInfo("郭大侠",...
It reads the object from the graph of objects stored while using FileInputStream. MethodreadObject()is the main method used to deserialize the object.The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its...
public class ObjectOutputStreamExample { public static void main(String[] args) { Employee emp = new Employee("Pankaj"); emp.setAge(35); emp.setGender("Male"); emp.setRole("CEO"); System.out.println(emp); try { FileOutputStream fos = new FileOutputStream("EmployeeObject.ser"); ...
); try { FileOutputStream fileOut = new FileOutputStream("person.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(person); // Manually call writeObject to serialize out.close(); fileOut.close(); FileInputStream fileIn = new FileInputStream("person.ser"); ...
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...
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");ObjectOutputStreamout=newObjectOutputStr...
// Serialize Object to XML Object obj = new Object(); JAXBContext jaxbContext = JAXBContext.newInstance(Object.class); Marshaller marshaller = jaxbContext.createMarshaller(); StringWriter stringWriter = new StringWriter(); marshaller.marshal(obj, stringWriter); ...
// 序列化对象到缓存文件publicstaticvoidserializeToCache(Object object,String cacheKey){try(ObjectOutputStream out=newObjectOutputStream(newFileOutputStream(cacheKey))){out.writeObject(object);}catch(IOException e){e.printStackTrace();}}// 从缓存文件中反序列化对象publicstaticObjectdeserializeFromCache(...