一、对象序列化(存储)
FileOutputStream fileStream = new FileOuputStream("file.ser");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(one);//Help one = new Help(); os.writeObject(two);
os.close();
要想类被序列化,必须实现Serializable:
public class Box implements Serializable{ private int x; transient String y; Animal a = new Animale(); ... }
public class Animal{ ... }x会被保存;y不会被序列化,transient标记的变量被跳过;a不会,因为Animal类没有实现Serializable。
二、解序列化
FileInputStream fileStream = new FileInputStream("file.ser");
ObjectInputStream is = new ObjectInputStream(fileStream);
Object one = is.readObject(); Object two = is.readObject();
Help oneHelp = (Hlep)one; Help twoHelp = (Hlep)two;
is.close();
三、文件读写
File myFile = new File("MyText.txt"); FileReader fileReader = new FileReader(myFile); BufferedReader reader = new BufferedReader(fileReader); while reader.readLine() != null reader.close();
File myFile = new File("1.txt"); FileWriter fileWriter = new FileWriter(myFile); BufferedWriter writer = new BufferedWriter(fileWriter); writer.write("hello"); writer.close();
File dir = new File("dir1"); dir.mkdir(); if(dir.idDirectory()){ String [] dirContents = dir.list(); for(int i = 0;i < dirContents.length;i++){ System.out.println(dirContents[i]); } } System.out.println(dir.getAbsolutePath()); dir.delete();
基础篇——序列化和文件的输入输出,布布扣,bubuko.com
原文:http://blog.csdn.net/fengxiaoke_fxk/article/details/38232777