IO流-字节流
IO流-体系结构
细节
:
输出流关联文件,文件如果不存在:会自动创建出来
如果文件存在:会清空现有的内容,然后再进行写入操作
/*
细节:
输出流关联文件,文件如果不存在:会自动创建出来
如果文件存在:会清空现有的内容,然后再进行写入操作
*/
//创建字节输出流对象,关联文件
FileOutputStream fos = new FileOutputStream("D:\\file_io\\A.txt");
//写出数据 一个字节
fos.write(97); //a
//字节数组
byte[] bys = {98,99,100};
fos.write(bys);
//字符串可以用getBytes方法
fos.write("你好".getBytes());
开启追加写入模式,在后面加个true
FileOutputStream fos = new FileOutputStream("D:\\file_io\\A.txt",true);
FileInputStream fis = new FileInputStream("D:\\file_io/A.txt");
int read;
while ((read=fis.read())!=-1){
System.out.println((char) read);
}
fis.close();
FileInputStream fis = new FileInputStream("D:\\file_io/A.txt");
byte[] bytes = new byte[2];
int length;
while ((length=fis.read(bytes))!=-1){
String s= new String(bytes,0,length);
System.out.println(s);
}
fis.close();
文件拷贝:
public class BufferedStreamDemo1 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\file_io/A.txt");
//1.创建字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream(fis);
//2.创建字节缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\file_io/test.txt"));
//3.读写操作
int i;
while ((i=bis.read())!=-1){
bos.write(i);
}
//4.关流
bis.close();
bos.close();
}
}
拷贝的效率测试(下图为缓冲流+自定义数组拷贝原理图):