/**
* 带缓冲功能(缓冲大小8K)的任意文件的复制(字节流)
* @author MJN
* @date 2011-10-03
*/
public class FileCopyWithBuffer {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
byte[] buf = new byte[8 * 1024];
int n = -1; //记录每次读取的实际字节长度
try {
in = new FileInputStream("1.jpg"); //文件1.jpg在工程的根目录下
out = new FileOutputStream("1_copy.jpg");
while ((n = in.read(buf)) != -1) {
/*
* 若写成out.write(buf), 则最后一次写入的总是8K字节
* 即使最后一次读的字节数不一定为8K
*/
out.write(buf, 0, n);
}
} catch (FileNotFoundException e) {
System.out.println("file not found.");
} catch (IOException e) {
System.out.println("error happened.");
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.flush();
out.close();
}
} catch (Exception e) {}
}
}
}
另外, 若要缓冲读取文件也可以用BufferedInputStream:
InputStream in = new BufferedInputStream(
new FileInputStream("in.txt"), 8 * 1024);
注意: 初始化时, 缓冲大小最好是1024的整数倍, 以使底层的操作达到最优化.
References:
NNU姜老师的课堂源码'java_course'