public class CopyFileCompare {
/**
* 1.普通文件流复制文件
* 耗时:十分钟过去了。。。
* @param source
* @param target
*/
public static void copyByFIS(String source, String target){
try(
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target)
) {
int b = -1;
while ((b = fis.read()) != -1){
fos.write(b);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 1.缓冲流复制文件
* 耗时:文件大小:103.0MB,耗时:1.162s
* @param source
* @param target
*/
public static void copyByBIS(String source, String target){
try(
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream( fos)
) {
int b = -1;
while ((b = bis.read()) != -1){
bos.write(b);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 3.缓冲流使用缓冲数组复制文件
* 耗时:文件大小:103.0MB,耗时:0.062s
* @param source
* @param target
*/
public static void copyByBISBuffer(String source, String target){
try(
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream( fos)
) {
int len = -1;
byte[] bytes = new byte[8*1024];
while ((len = bis.read(bytes)) != -1){
bos.write(bytes,0,len);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 4.NIO复制文件
* 耗时:文件大小:103.0MB,耗时:0.072s
* @param source
* @param target
*/
public static void copyByNIO(String source, String target){
File sourceFile = new File(source);
File targetFile = new File(target);
try(
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel()
) {
ByteBuffer buf = ByteBuffer.allocate(8*1024);
while (inChannel.read(buf) != -1) {
buf.flip();
while (outChannel.write(buf) != 0);
buf.clear();
}
outChannel.force(true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 获取文件大小MB
* @param fileName
* @return
*/
public static double getFileSize(String fileName){
File file = new File(fileName);
long length = file.length();
double size = length / 1024 / 1024;
int temp = (int)(size * 100);
return temp / 100.0;
}
public static void main(String[] args) {
String source = "/Users/tom/Documents/M1 软件包/zulu JDK/zulu8.64.0.19-ca-jdk8.0.345-macosx_aarch64.dmg";
String target = "/Users/tom/Documents/M1 软件包/zulu JDK/zulu8_copy.dmg";
long start = System.currentTimeMillis();
// 复制文件
copyByBISBuffer(source,target);
long end = System.currentTimeMillis();
double size = getFileSize(source);
double time = (end - start)/1000.0;
System.out.println("复制完成,文件大小:" + size + "MB,耗时:" + time + "s");
}
}
java使用IO流进行文件复制&性能比较
于 2022-09-17 17:25:39 首次发布