I/O流 - 字符流和字节流
一、字节流
1、字节输出流 OutputStream 往指定文件写数据
常用方法:
close():释放资源
flush():刷新流,并强制写出所有的缓冲的输出字节
write(byte[] b):将指定的 byte 数组写入到输出流
write(byte[] b,int off,int len):将指定byte 数组的指定部分写入到输出流
write(int b):将指定的字符写入到输出流
注意 OutputStream 是接口,要用他的实现类例如 FileOutputStream
FileOutputStream 的构造方法:
FileOutputStream fos = newFileOutputStream(Stirng path);
FileOutputStream fos = newFileOutputStream(File file);
续写, 默认false 不续写 ,续写用 false
FileOutputStream fos = newFileOutputStream(Stirng path,boolean append);
FileOutputStream fos = newFileOutputStream(File file,boolean append);
2、字节输入流 IntputStream 从指定文件读取数据
常用方法:
read():读入一个字节
read(byte[] b):读取 读取指定字节数组的大小
注意:IntputStream 是接口,用他的实现类例如 FileIntputStream
使用字节流复制文件:
1 // 明确数据源 2 File f2 = new File("D:\\demo0723\\lifecycle.png"); 3 FileInputStream fis = new FileInputStream(f2); 4 // 目的地 5 FileOutputStream fos = new FileOutputStream("D:\\demo0723\\a\\lifecycle(2).png"); 6 byte[] b = new byte[1024]; 7 int len2 = 0; 8 while ((len = fis.read(b)) != -1) { 9 fos.write(b,0,len); 10 } 11 fis.close(); 12 fos.close();
二、字符流
1、字节输入流:Reader
Reader 是接口,用他的实现类,例如 FileReader
常用方法:read():读取一个字节
read(char[] char):读取指定char数组的长度
FileReader 类:
构造方法:
FileReader fr = new FileReader(File file);
FileReader fr = new FileReader(String path);
2、字节输出流:Write
Write 是接口,用他的实现类,例如 FileWriter
常用方法:
write(char[] char):写入指定的char 数组
write(char[] char,int off,int len):写入指定的char 数组 的指定长度
write(int c):写入指定的单个字符
write(String str):写入指定的字符串
write(String str,int off,int len):写入指定字符串的指定长度
FileWriter 类:
构造方法:
FileWrite fw = new FileWrite(File file);
FileWrite fw = new FileWrite(String path);
续写 默认false 不续写 ,续写用 false
FileWrite fw = new FileWrite(File file,boolean append);
FileWrite fw = new FileWrite(String path,boolean append);
flush() 和 close()区别:
flush() :刷新流,强制把缓冲的字符写入文件,但是还可以继续用
close():有flush() 的功能,但是使用后流将不可再用
使用字节流复制文件
1 // 使用字符流复制 2 FileReader fr = new FileReader(f); 3 FileWriter fw = new FileWriter("D:\\demo0723\\a\\lifecycle(1).png"); 4 5 char[] ch = new char[1024]; 6 int len = 0; 7 while ((len = fr.read(ch)) != -1) { 8 fw.write(ch, 0, len); 9 } 10 fw.close(); 11 fr.close();
如何区分 字节和字符流
字节流:以Stream 结尾
字符流:以Reader和Writer结尾