BufferedInputStream继承于FilterInputStream,提供缓冲输入流功能。缓冲输入流相对于普通输入流的优势是,它提供了一个缓冲数组,每次调用read方法的时候,它首先尝试从缓冲区里读取数据,若读取失败(缓冲区无可读数据),则选择从物理数据源(譬如文件)读取新数据(这里会尝试尽可能读取多的字节)放入到缓冲区中,最后再将缓冲区中的内容部分或全部返回给用户.由于从缓冲区里读取数据远比直接从物理数据源(譬如文件)读取速度快。
public class Test1 {
BufferedInputStream bufferedInputStream;
BufferedOutputStream bufferedOutputStream;
byte[] bytes = new byte[1024];
int n = 0;
public void transWriteByBuf(FileInputStream fileInputStream,FileOutputStream fileOutputStream) throws IOException {
// TODO Auto-generated method stub
n = 0;
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
while ((n = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, n);
}
bufferedInputStream.close();
bufferedOutputStream.close();
fileInputStream.close();
fileOutputStream.close();
}
public void transReadByBuf(FileInputStream fileInputStream) throws IOException {
// TODO Auto-generated method stub
bufferedInputStream = new BufferedInputStream(fileInputStream);
while ((n = bufferedInputStream.read(bytes)) != -1) {
System.out.print(new String(bytes, 0, n));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Test1 test1 = new Test1();
test1.transReadByBuf(new FileInputStream(new File("I:\\Java\\Mars\\IndiaCovid-19.txt")));
test1.transWriteByBuf(new FileInputStream(new File("I:\\Java\\Mars\\IndiaCovid-19.txt")),new FileOutputStream(new File("three.txt")));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}