缓冲字节流、缓冲字符流

作用:提高读写效率

package com.study02;
//缓冲字节流

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestCopy {
public static void main(String[] args) throws IOException {
//1.数据源

FileInputStream fis = new FileInputStream("aaaa.txt");
//2.目的文件
FileOutputStream fos = new FileOutputStream("bbb.txt");
//3.操作

//使用缓冲
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);

byte[] by = new byte[1024];
int len = 0;
while((len = bis.read(by))!=-1) {
bos.write(by,0,len);
bos.flush();
}
//4.关闭空间:关闭高层节点流即可

bos.close();
bis.close();
}
}

缓冲字符流

package com.study02;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class testBuffered {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw= null;
try {
br = new BufferedReader(new FileReader("aaa.txt"));
bw = new BufferedWriter(new FileWriter("bbb.txt"));
String line = null;
while((line=br.readLine())!=null){
bw.write(line);
bw.newLine();//换行
bw.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (bw!=null) {
bw.close();
}

if (br!=null) {
br.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

纯文本情况下用字符流,其他情况用字节流

猜你喜欢

转载自www.cnblogs.com/LuJunlong/p/11830512.html