黑马程序员技术交流社区
标题:
字节流复制文件四种方式对比
[打印本页]
作者:
hero_king
时间:
2016-5-30 23:30
标题:
字节流复制文件四种方式对比
四种方式分别是
1:基本字节流一次读取一个字节;
2:基本字节流一次读取一个字节数组;:
3:高效字节流一次读取一个字节;
4:高效字节流一次读取一个字节数组;
实验证明第四种方式效率最高。
<p>
/*
* 将 F:\\Visual_C++网络编程.pdf 复制到当前项目目录下,
* 要求使用字节流的四种方式
*/
public class Demo3 {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
// 共耗时192236毫秒
// method1("F:\\Visual_C++网络编程.pdf", "1.pdf");
// 共耗时346毫秒
method2("F:\\Visual_C++网络编程.pdf", "2.pdf");
// 共耗时1211毫秒
method3("F:\\Visual_C++网络编程.pdf", "3.pdf");
// 共耗时51毫秒
method4("F:\\Visual_C++网络编程.pdf", "4.pdf");</p><p> long end = System.currentTimeMillis();
System.out.println("共耗时" + (end - start) + "毫秒");
}</p><p> private static void method4(String src, String dest) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
src));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(dest));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bis.close();
bos.close();
}</p><p> private static void method3(String src, String dest) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
src));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(dest));
int by = 0;
while ((by = bis.read()) != -1) {
bos.write(by);
}
bis.close();
bos.close();
}</p><p> private static void method2(String src, String dest) throws IOException {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
fos.write(bys, 0, len);
}
fis.close();
fos.close();
}</p><p> // private static void method1(String src, String dest) throws IOException {
// FileInputStream fis = new FileInputStream(src);
// FileOutputStream fos = new FileOutputStream(dest);
// int by = 0;
// while ((by = fis.read()) != -1) {
// fos.write(by);
// }
// fis.close();
// fos.close();
// }
}
</p><p> </p>
复制代码
作者:
lifeiwangyue
时间:
2016-5-30 23:48
来学习下
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2