对象流
序列化
public static void main(String[] args) throws Exception { //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存 String filePath = "e:\\data.dat"; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath)); //序列化数据到 e:\data.dat oos.writeInt(100);// int -> Integer (实现了 Serializable) oos.writeBoolean(true);// boolean -> Boolean (实现了 Serializable) oos.writeChar('a');// char -> Character (实现了 Serializable) oos.writeDouble(9.5);// double -> Double (实现了 Serializable) oos.writeUTF("韩顺平教育");//String //保存一个dog对象 oos.writeObject(new Dog("旺财", 10, "日本", "白色")); oos.close(); System.out.println("数据保存完毕(序列化形式)"); }View Code
反序列化
public static void main(String[] args) throws IOException, ClassNotFoundException { //指定反序列化的文件 String filePath = "e:\\data.dat"; ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath)); //读取 //老师解读 //1. 读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致 //2. 否则会出现异常 System.out.println(ois.readInt()); System.out.println(ois.readBoolean()); System.out.println(ois.readChar()); System.out.println(ois.readDouble()); System.out.println(ois.readUTF()); //dog 的编译类型是 Object , dog 的运行类型是 Dog Object dog = ois.readObject(); System.out.println("运行类型=" + dog.getClass()); System.out.println("dog信息=" + dog);//底层 Object -> Dog //这里是特别重要的细节: //1. 如果我们希望调用Dog的方法, 需要向下转型 //2. 需要我们将Dog类的定义,放在到可以引用的位置 Dog dog2 = (Dog)dog; System.out.println(dog2.getName()); //旺财.. //关闭流, 关闭外层流即可,底层会关闭 FileInputStream 流 ois.close(); }View Code
防止读取乱码(指定编码)
public static void main(String[] args) throws IOException { String filePath = "e:\\a.txt"; //解读 //1. 把 FileInputStream 转成 InputStreamReader //2. 指定编码 gbk //InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk"); //3. 把 InputStreamReader 传入 BufferedReader //BufferedReader br = new BufferedReader(isr); //将2 和 3 合在一起 BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(filePath), "gbk")); //4. 读取 String s = br.readLine(); System.out.println("读取内容=" + s); //5. 关闭外层流 br.close(); }View Code
指定输出编码
public static void main(String[] args) throws IOException { String filePath = "e:\\hsp.txt"; String charSet = "utf-8"; OutputStreamWriter osw = new OutputStreamWriter( new FileOutputStream(filePath), charSet ); osw.write("hi, 韩顺平教育"); osw.close(); System.out.println("按照 " + charSet + " 保存文件成功~"); }View Code