一:缓冲流
1:定义:在内存与硬盘之间创建一个大小合适的缓冲区,当内存和硬盘进行数据访问时,能提高访问硬盘的次数,提高效率。
2:分类:缓冲分为字节缓冲流(BufferedInputStream和BufferedOutputStream)和字符缓冲流(BufferedReader和BufferedWrite)。
3:缓冲流对字节文件拷贝的应用(代码示例):
public class CopyFile {
public static void main(String[] args) throws IOException {
CopyFile c = new CopyFile();
c.copy();
}
public void copy() throws IOException {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("C:\\Users\\huangxiong\\Desktop\\test.txt"));// 对输入流进行包装
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("C:\\Users\\huangxiong\\Desktop\\test1.txt"));// 对输出流进行包装
int len;
while ((len = bis.read()) != -1) {
bos.write(len);
}
bis.close();
bos.close();
}
}
4:缓冲流属于包装流,只能对已有的流进行包装,使原来的流更加强大,执行效率更高,不能关联文件。
二:数据流(DataInputStream,DataOutputStream)
1:定义:数据流是对8大基本数据类型的数据进行内存与硬盘之间互相访问的流,属于包装流,包装后使原来的流传输数据更加方便
2:分类:数据流只有字节流,没有字符流。
3:数据流对文件的拷贝(代码示例)
public void copy1() throws IOException{
int a = 201400;
long b = 1000000000;
boolean c = true;
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream
(new FileOutputStream("C:\\Users\\huangxiong\\Desktop\\test.txt")));//用缓冲流和数据流分别对FileOuyputStream进行包装
dos.writeInt(a);
dos.writeLong(b);
dos.writeBoolean(c);
dos.close(); //流一结束,就关闭流
DataInputStream dis = new DataInputStream(
new BufferedInputStream(new FileInputStream("C:\\Users\\huangxiong\\Desktop\\test.txt")));
int a1 = dis.readInt();
long b1 = dis.readLong();
boolean c1 = dis.readBoolean();
System.out.println(a1);
System.out.println(b1);
System.out.println(c1);
dis.close();
}
三:对象流(ObjectInputStream,ObjectOutputStream)
1:定义:对象流传输的是一个对象,在我们需要保存一个对象的很多属性的时候,用对象流可以简化代码,更加方便2:分类:输入对象流和输出对象流
2:对象流也属于包装流,包装后使原来的流具有对对象进行读写的功能
3:对象流实现对象的拷贝(代码示例)
try {
//把对象写入文件
ArrayList list = new ArrayList();
Student stu = new Student("张三",30);
list.add(stu);
//对象流操作,直接写入或者读入对象
FileOutputStream fos = new FileOutputStream("test_4.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//可以直接写出对象
oos.writeObject(list);
oos.flush();
oos.close();
//从文件中读取对象
FileInputStream fis = new FileInputStream("test_4.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
@SuppressWarnings("unchecked")
ArrayList stuList = (ArrayList)ois.readObject();
ois.close();
for (int i = 0; i < stuList.size(); i++) {
Student stu1 = stuList.get(i);
System.out.println(stu1.name+" "+stu1.age);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Student类:
package com.huaxin.io;
import java.io.Serializable;
public class Student implements Serializable{
public String name;
public int age;
public Student(String name,int age){
this.name = name;
this.age = age;
}
}
注意事项:对象流在读写对象时候,必须对对象进行序列化,也就是该对象必须 implements Serializable,这是为了将对象写成特殊序列的字节码文件,读文件的时候,可以还原这个对象。
---------------------
作者:大大的馒头
来源:CSDN
原文:https://blog.csdn.net/xxx77889900/article/details/52911558
版权声明:本文为博主原创文章,转载请附上博文链接!