Home > Java > javaTutorial > Java serialization and deserialization

Java serialization and deserialization

高洛峰
Release: 2016-11-16 11:59:14
Original
1733 people have browsed it

Java对序列化提供了非常方便的支持,在定义类的时候,如果想让对象可以被序列化,必须实现 implements Serializable

比如,对已存在的wang.txt进行序列化,得到的字节输出到wang1.txt文件中

package Serializable;
/*
 * 文本文件的序列化
 */
import java.io.*;
 
public class test  implements Serializable
{  
 public static void main(String[] args) throws ClassNotFoundException  
 {  
     File file=new File("D:\\wang.txt");
     File fi = new File("D:\\wang1.txt");  
  try  
  {  
   file.createNewFile();  
  }  
  catch(IOException e)  
  {  
   e.printStackTrace();  
  }  
  try  
  {  
   //序列化
   FileOutputStream fos = new FileOutputStream(fi);  
   ObjectOutputStream oos = new ObjectOutputStream(fos);  
   oos.writeObject(file);  
   oos.flush();  
   oos.close();  
   fos.close();  
    
   //反序列化
   FileInputStream fis = new FileInputStream(fi);  
   ObjectInputStream ois = new ObjectInputStream(fis);  
   File file1= (File) ois.readObject();    //反序列化一个对象
  }  
  catch (IOException e)  
  {  
   e.printStackTrace();  
  }               
 }  
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template