事实证明BufferedInputStream比FileInputStream快,而不是老师说的那个结论批量比缓冲块!!如果批量缓冲与批量相比呢?代码如下
/**
* 批量读写
*
* @param srcFile
* @param destFile
*/
public static void copyFile(File srcFile, File destFile) {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
if (!srcFile.exists()) {
throw new IllegalArgumentException("源目标文件不存在!!!");
}
if (!srcFile.isFile()) {
throw new IllegalArgumentException("源目标不是文件类型!!!");
}
try {
inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(destFile);
byte[] bytes = new byte[8 * 1024];
int length = 0;
while ((length = inputStream.read(bytes, 0, bytes.length)) != -1) {
outputStream.write(bytes, 0, length);
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 缓冲批量读写
*
* @param srcFile
* @param destFile
*/
public static void copyFileByBuffer(File srcFile, File destFile) {
FileInputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
FileOutputStream outputStream = null;
BufferedOutputStream bufferedOutputStream = null;
if (!srcFile.exists()) {
throw new IllegalArgumentException("源目标文件不存在!!!");
}
if (!srcFile.isFile()) {
throw new IllegalArgumentException("源目标不是文件类型!!!");
}
try {
inputStream = new FileInputStream(srcFile);
bufferedInputStream = new BufferedInputStream(inputStream);
outputStream = new FileOutputStream(destFile);
bufferedOutputStream = new BufferedOutputStream(outputStream);
byte[] bytes = new byte[8 * 1024];
int length = 0;
while ((length = bufferedInputStream.read(bytes, 0, bytes.length)) != -1) {
bufferedOutputStream.write(bytes, 0, length);
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedOutputStream.close();
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}测试代码:
public class IOUtilTest {
public static void main(String[] args) throws IOException {
File srcFile1 = new File("F:\\学习资料\\1-1和2.mp4");
File destFile1 = new File("F:\\1.mp4");
long beg1 = System.currentTimeMillis();
IOUtil.copyFile(srcFile1,destFile1);
long end1 = System.currentTimeMillis();
System.out.println("批量读取时间毫秒:"+(end1 - beg1));//768
File destFile2 = new File("F:\\2.mp4");
long beg2 = System.currentTimeMillis();
IOUtil.copyFileByBuffer(srcFile1,destFile2);
long end2 = System.currentTimeMillis();
System.out.println("批量缓冲读取时间毫秒:"+(end2 - beg2));//130
}
}源目标文件大小:60.4M