一、对象序列化(存储)
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();
基础篇——序列化和文件的输入输出
时间: 2024-10-12 18:33:37