1、ObjectInputStream和ObjectOutputStream
ObjectInputStream和ObjectOutputStream分别与FileInputStream和FileOutputStream一起使用时,可以为应用程序提供对对象的持久存储。我们把对象以某种特定的编码格式写入称之为“序列化”。把写入的编码格式内容还原成对象称之为“反序列化”。被序列化的对象必须实现Serializable接口。
package com.iotek.otherio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectInputOutputDemo {
public static void main(String[] args) throws IOException {
/*Student student = new Student("zhangsan", 30);
FileOutputStream fos = new FileOutputStream("f:\\test\\1.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fos);
objectOutputStream.writeObject(student);//把对象序列化到指定的文件输出流中
objectOutputStream.close();//释放资源*/
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("f:\\test\\1.txt"));
try {
Student student = (Student)objectInputStream.readObject();
System.out.println(student);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Student implements Serializable{//需要实现Serializable接口
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
2、InputStreamReader和OutputStreamWriter
转换流是指将字节流与字符流之间进行转换。转换流的出现方便了对文件的读写,它在字符流与字节流之间架起了一座桥梁,使原本毫无关联的两种操作能够进行转化,提高了程序的灵活性。字节流中的数据都是字符时,转化成字符流操作更高效。如果使用非默认编码保存文件或者读取文件时,需要用到转换流,因为字节流的重载构造方法中有指定编码格式的参数,而FileReader与FileWriter是默认编码的文本文件。
package com.iotek.otherio;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class InputStreamWriterReaderDemo {
public static void main(String[] args) throws IOException {
/*OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("f:\\test\\2.txt"), "utf-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write("您好");
bw.close();*/
/*BufferedReader br = new BufferedReader(new FileReader("f:\\test\\2.txt"));
String line = null;
while((line = br.readLine())!=null){
System.out.println(line);
}
br.close();*/
BufferedReader bReader = new BufferedReader(new InputStreamReader(new FileInputStream("f:\\test\\2.txt"),"utf-8"));
String line = null;
while((line = bReader.readLine())!=null){
System.out.println(line);
}
bReader.close();
}
}