序列化与文件的输入输出
1.如果要让类能够被序列化,首先需要实现Serializable
import java.io.*;
public class Box implements Serializable { private int width; private int height; private transient int id; public void setId(int id) { this.id = id; } public void setWidth(int width) { this.width = width; } public void setHeight(int height) { this.height = height; } }
2.将序列化对象写入文件
public static void main(String[] args) { Box myBox = new Box(); myBox.setHeight(20); myBox.setWidth(50); myBox.setId(1); try { //1.创建存取文件的FileOutputStream对象 FileOutputStream fs = new FileOutputStream("box.ser"); //2.创建ObjectOutputStream ObjectOutputStream os = new ObjectOutputStream(fs); //3.写入对象 os.writeObject(myBox); //4.关闭连接 os.close(); } catch (Exception e) { e.printStackTrace(); } }
3.解序列化:还原对象
public static void main(String[] args) { try { //1.创建FileInputStream ,读取文件 FileInputStream fileStream = new FileInputStream("box.ser"); //2.创建ObjectInputStream ,链接FileInputStream ObjectInputStream os = new ObjectInputStream(fileStream); //3.读取对象 Object o = os.readObject(); //4.转换对象类型 Box box = (Box) o; System.out.println(box.toString()); //5.关闭ObjectInputStream ,FileInputStream 自动跟着关掉 os.close(); } catch (Exception e) { e.printStackTrace(); } }
读取文本文件
public static void main(String[] args) { try { File myFile = new File("HELP.md"); //1.FileReader:连接到文本文件的串流 FileReader fileReader = new FileReader(myFile); //2.BufferedReader:将FileReader链接到BufferedReader获取更高效率。 //BufferedReader只会在缓冲区堵孔的时候才会去磁盘读取 BufferedReader reader = new BufferedReader(fileReader); String line = null; while ((line=reader.readLine())!=null){ System.out.println(line); } reader.close(); } catch (Exception ex) { ex.printStackTrace(); } }
懵懵懂懂迷迷糊糊

浙公网安备 33010602011771号