转换流
- 输入流:InputStreamReader
- 输出流:OutputStreamWriter
// method1();
// method2();
}
private static void method2() throws IOException {
// 如果编码格式是GBK,与IDEA编码格式不同,则需要进行转换(第二个参数写码表名称)
InputStreamReader isr = new InputStreamReader(new FileInputStream("C:\\Users\\daizelong\\Desktop\\lilpeep.txt"),"UTF-8");
int ch;
while ((ch = isr.read())!=-1){
System.out.print((char) ch);
}
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("C:\\Users\\daizelong\\Desktop\\lilpeep4EVER.txt"),"UTF-8");
osw.write("lilpeep4ever&crybaby");
osw.close();
}
private static void method1() throws IOException {
//因为系统上的文本内容自动保存的是UTF-8编码格式,故输出并未出现乱码。
FileReader fr = new FileReader("C:\\Users\\daizelong\\Desktop\\lilpeep.txt");
int b;
while ((b = fr.read())!=-1){
System.out.print((char) b);
}
fr.close();
}
对象操作流
可以把对象以字节的形式写到本地文件,直接打开文件是无法读懂的,需要再次用对象操作流读到内存中。
如果想要这个类的对象能被序列化,那么这个类必须要实现一个接口,serializable
并在对象类中定义序列号
只要一个类实现了这个serializable接口,那么就表示这个类的对象可以被序列化。
序列化
User user = new User("dzl666","2233");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Bhpractice\\src\\aResumeitheima\\Day_11\\对象操作流\\a.txt"));
oos.writeObject(user);
oos.close();
反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Bhpractice\\src\\aResumeitheima\\Day_11\\对象操作流\\a.txt"));
//两种方法均可用
Object o = ois.readObject();
// User o = (User) ois.readObject();
System.out.println(o);
ois.close();
小练习:
创建多个Javabean类对象写到文件中,并再次读取到内存。
方法一:
public static void main(String[] args) throws IOException, ClassNotFoundException {
//创建对象
Student s1= new Student("故友",23);
Student s2= new Student("如巾",21);
Student s3= new Student("可豪",25);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Bhpractice\\src\\aResumeitheima\\Day_11\\对象操作流\\b.txt"));
oos.writeObject(s1);
oos.writeObject(s2);
oos.writeObject(s3);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Bhpractice\\src\\aResumeitheima\\Day_11\\对象操作流\\b.txt"));
while(true){
try {
Object o = ois.readObject();
System.out.println(o);
} catch (EOFException e) {
break;
}
}
}
方法二:
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student s1= new Student("故友",23);
Student s2= new Student("如巾",21);
Student s3= new Student("可豪",25);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Bhpractice\\src\\aResumeitheima\\Day_11\\对象操作流\\b.txt"));
ArrayList<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
//以集合的形式写入
oos.writeObject(list);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Bhpractice\\src\\aResumeitheima\\Day_11\\对象操作流\\b.txt"));
ArrayList<Student> list2 = (ArrayList<Student>) ois.readObject();
for (Student student : list) {
System.out.println(student);
}
ois.close();
}