在Java文件操作中,有缓冲流的操作 BufferedInputStream 和 BufferedOutputStream(操作字节流) 以及 BufferReader 和 BufferedWriter (操作字符流)方法,这里我们采用较常用的字节缓冲流进行讨论,字节缓冲流旨在提高文件传输的速度,使用这个会比FileInputStream 和 FileOutputStream 要快。具体实例如下:
这个例子我们直接按照Buffer系方法写了一个通用的工具类,如下:
// 使用BufferedInputStream与BufferedOutputStream实现非文本文件的测试、
//这里的文件可以为文本也可以为其他类型的文件。
public void testBufIO(String src, String dst) {
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
// 提供读入写出的文件
File file1 = new File(src);
File file2 = new File(dst);
// 创建相应的节点流FileInputStream FileOutputStream
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
// 3 将创建的节点流作为形参传递到缓冲流构造器
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
// 文件的复制过程
byte[] b = new byte[1024];
int len;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();//刷新清空
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
使用以上方法可以实现快速的文件读和写。希望对大家有帮助。