四种方式实现文件的复制
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 需求:把d:\\1.jpg", 复制到"e:\\2.jpg中
*
* 字节流四种方式复制文件:
* 基本字节流一次读写一个字节: 共耗时:117235毫秒
* 基本字节流一次读写一个字节数组:共耗时:156毫秒
* 高效字节流一次读写一个字节:共耗时:1141毫秒
* 高效字节流一次读写一个字节数组:共耗时:47毫秒
*/
public classCopyFile0 {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
// method1("d:\\1.jpg", "e:\\2.jpg"); //共耗时:121474毫秒
// method2("d:\\1.jpg", "e:\\2.jpg"); //共耗时:146毫秒
// method3("d:\\1.jpg", "e:\\2.jpg"); //共耗时:604毫秒
method4("d:\\1.jpg","e:\\2.jpg"); //共耗时:44毫秒
long end = System.currentTimeMillis();
System.out.println("共耗时:" + (end - start) + "毫秒");
}
// 高效字节流一次读写一个字节数组:
public static void method4(StringsrcString, String destString)
throws IOException {
BufferedInputStreambis = newBufferedInputStream(new FileInputStream(
srcString));
BufferedOutputStreambos = newBufferedOutputStream(
newFileOutputStream(destString));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys))!= -1) {
bos.write(bys,0, len);
}
bos.close();
bis.close();
}
// 高效字节流一次读写一个字节:
public static void method3(StringsrcString, String destString)
throws IOException {
BufferedInputStreambis = newBufferedInputStream(new FileInputStream(
srcString));
BufferedOutputStreambos = newBufferedOutputStream(
newFileOutputStream(destString));
int by = 0;
while ((by = bis.read()) !=-1) {
bos.write(by);
}
bos.close();
bis.close();
}
// 基本字节流一次读写一个字节数组
public static void method2(StringsrcString, String destString)
throws IOException {
FileInputStreamfis = newFileInputStream(srcString);
FileOutputStreamfos = newFileOutputStream(destString);
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys))!= -1) {
fos.write(bys,0, len);
}
fos.close();
fis.close();
}
// 基本字节流一次读写一个字节
public static void method1(StringsrcString, String destString)
throws IOException {
FileInputStreamfis = newFileInputStream(srcString);
FileOutputStreamfos = newFileOutputStream(destString);
int by = 0;
while ((by = fis.read()) !=-1) {
fos.write(by);
}
fos.close();
fis.close();
}
}