I/O框架
什么是流
流的分类
- 按方向:
1)输入流:将<存储设备>中的内容读入<内存>中
2)输出流:将<内存>中的内容写入<存储设备>中
- 按单位:
1)字节流:以字节为单位,可以读写所有数据
2)字符流:以字符为单位,只能读写文本数据
- 按功能:
1)节点流:具有实际传输数据的读写功能
2)过滤流:在节点流的基础上增强功能
字节流
字节流的父类抽象类
- 用来读取文件的字节流
![]()
public class Test {
public static void main(String[] args) throws Exception{
//创建FileInputStream对象,并指定文件路径
FileInputStream file = new FileInputStream("d:\\aaa.txt");
//1.单个字节读取file.read();该方法只能读取一个字节,用循环
/*
int n = 0;
while ((n = file.read())!=-1){
System.out.print((char) n);
}
*/
//2.一次读取多个字节
byte[] by = new byte[256];
int count = 0;
while((count = file.read(by))!=-1){
System.out.println(new String(by,0,count));
}
file.close();
System.out.println("执行完毕");
}
}
FileOutputStream
public class Test {
public static void main(String[] args) throws Exception{
//创建文件字节输出流对象,加true后写入的字节不会被覆盖,会叠加
FileOutputStream fos = new FileOutputStream ("d:\\aaa",true);
//写入单个字节流
fos.write(97);
fos.write('b');
fos.write('c');
//一次写入多个字节流
String str = "helloworld";
fos.write(str.getBytes());//getBytes获取字符串对应的字节数组
fos.close();
System.out.println("执行完毕");
}
}
字节流复制文件
使用文件字节流实现文件的复制
public class Test {
public static void main(String[] args) throws Exception{
//创建对象,文件字节流输入
FileInputStream fis = new FileInputStream("d:\\001.jpg");
//文件字节流输出
FileOutputStream fos = new FileOutputStream("d:\\002.jpg");
//一边读一边写
byte[] buf = new byte[1024];//一次可读取1024字节
int count = 0;//保存实际读取的字节个数
while ((count=fis.read(buf))!=-1){
fos.write(buf,0,count);
}//实际是自己写了一个缓冲区
System.out.println("执行完毕");
fis.close();
fos.close();
}
}
字节缓冲流
- 提高IO效率,减少访问磁盘的次数
- 数据存储在缓冲区中,flush是将缓存区的内容写入文件中,也可以直接close
-
public class Test {
public static void main(String[] args) throws Exception {
//使用字节缓冲流读取
FileInputStream fis = new FileInputStream("d:\\aaa.txt");
//缓冲流的目的是增强底层流
BufferedInputStream bis = new BufferedInputStream(fis);
//读取后放到缓冲区,以提高效率
int date = 0;
while ((date=bis.read())!=-1){
System.out.print((char) date);
}
bis.close();
}
}
public class Test {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("d:\\aaa.txt",true);
BufferedOutputStream bos = new BufferedOutputStream(fos);//字节缓冲输出流
for (int i = 0; i <10 ; i++) {
bos.write("helloworld\r\n".getBytes());//写入8k缓冲区
bos.flush();//刷新到硬盘
}
bos.close();//内部会调用flush方法,如没写flush方法,在写入close后也会将字节写入硬盘
System.out.println("执行完毕");
}
}