<div yne-bulb-block="paragraph" style="white-space: pre-wrap;"><span style="font-family:Arial;"><span style="font-size: 13px; line-height: 19.5px;">带缓冲的作用:</span></span></div><div yne-bulb-block="paragraph" style="white-space: pre-wrap; line-height: 1.5; font-size: 14px;"><span style="font-size: 13px; font-family: Arial;"><span style="white-space:pre"> </span>不带缓冲的操作,每读一个字节就要写入一个字节,由于涉及磁盘的IO操作相比内存的操作要慢很多,所以不带缓冲的流效率很低。带缓冲的流,可以一次读很多字节,但不向磁盘中写入,只是先放到内存里。等凑够了缓冲区大小的时候一次性写入磁盘,这种方式可以减少磁盘操作次数,但是内存会占用的多,速度就会提高很多!</span></div>
<pre name="code" class="java">import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileUtils {
/*
* srcFile 源文件
* destFile 目标文件
* num 定制缓冲数组大小(单位KB)
*/
public static void copyFile(File srcFile, File destFile, int num) {
if (!srcFile.exists()) {
throw new IllegalArgumentException(srcFile + "不存在");
}
if (!srcFile.isFile()) {
throw new IllegalArgumentException(srcFile + "不是文件");
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
byte[] buf = new byte[num * 1024];
int len = 0;
try {
bis = new BufferedInputStream(new FileInputStream(srcFile));
bos = new BufferedOutputStream(new FileOutputStream(destFile));
while ((len = bis.read(buf, 0, buf.length)) != -1) {
bos.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void copyTextFile(File srcFile, File destFile, int num) {
BufferedReader br = null;
BufferedWriter bw = null;
char[] cbuf = new char[num * 1024];
int len = 0;
try {
br = new BufferedReader(new FileReader(srcFile));
bw = new BufferedWriter(new FileWriter(destFile));
while ((len = br.read(cbuf, 0, cbuf.length)) != -1) {
bw.write(cbuf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}