关于字节流的总结:
首先,使用字节流不能读取中文,不然会出现乱码的情况。
一、读取
1.单个读取
package com.demoBufferzijie;
import java.io.FileInputStream;
import java.io.IOException;
public class InPutDemo01 {
public static void main(String[] args) throws IOException {
FileInputStream fis= new FileInputStream("day11\\aaa.txt");
int b;
//读取文件中多个字节
while ((b=fis.read())!=-1){
System.out.println((char)b);
}
}
}
2.使用小数组读取
package com.demoBufferzijie;
import java.io.FileInputStream;
import java.io.IOException;
public class InPutDemo03 {
//字节流读数据(一次读一个字节数组数据)
public static void main(String[] args) throws IOException {
FileInputStream fis= new FileInputStream("day11\\aaa.txt");
byte[] bytes= new byte[1024];
int len;
//读取文件中多个字节
while ((len=fis.read(bytes))!=-1){
System.out.println(new String(bytes,0,len));
}
}
}
二、复制
1.使用字符输入流和字符输出流实现
package com.demoBufferzijie;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class InPutDemo04 {
public static void main(String[] args) throws IOException {
//创建了字符输入流 负责读
FileInputStream fis= new FileInputStream("day11\\aaa.txt");
//创建了字符输出流 负责写
FileOutputStream fos= new FileOutputStream("day11\\bbb.txt");
int b;
//读取文件中多个字节
while ((b=fis.read())!=-1){
fos.write(b);
}
fis.close();
fos.close();
System.out.println("拷贝成功");
}
}
2.使用字节缓冲流实现
package com.demoBufferzijie;
import java.io.*;
public class BufferedOutputStreamDemo1 {
//复制文件 最终代码
public static void main(String[] args) throws IOException {
BufferedOutputStream bos= new BufferedOutputStream(new FileOutputStream("day11\\ccc.txt"));
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("day11\\aaa.txt"));
int b;
while ((b=bis.read())!=-1){
bos.write(b);
}
bis.close();
bos.close();
}
}
注意:
使用时有两个小问题:
-
字节流写数据如何实现换行
- windows:\r\n
- linux:\n
- mac:\r
-
字节流写数据如何实现追加写入
- public FileOutputStream(String name,boolean append)
- 创建文件输出流以指定的名称写入文件。如果第二个参数为true ,则字节将写入文件的末尾而不是开头