package com.zmm.copy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class IOcopyTest {
public static void main(String[] args) throws IOException {
File sourceFile = new File("D://poju.mp4");
File targetFile = new File("D://666.mp4");
copyFileByStream(sourceFile, targetFile);
// copyFileByChannel(sourceFile, targetFile);
// copyFileByFilesClass("D://poju.mp4", "D://896.mp4");
}
/**
* 方式1 java.io类库中的传统输入输出流
*
* @param source
* @param target
* @throws IOException
*/
private static void copyFileByStream(File source, File target) throws IOException {
long start = System.currentTimeMillis();
try (InputStream fileInputStream = new FileInputStream(source);
OutputStream fileOutputStream = new FileOutputStream(target);) {
byte[] buffer = new byte[1024];
int length;
int i = 0;
while ((length = fileInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
i++;
}
System.out.println("i+++=" + i);
System.out.println("cost time:" + (System.currentTimeMillis() - start));
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* 方式2 java.nio类库中的文件通道方式 transferTo/transferFROM
*
* @param source
* @param target
* @throws IOException
*/
private static void copyFileByChannel(File source, File target) throws IOException {
long start = System.currentTimeMillis();
try (FileChannel inputChannel = new FileInputStream(source).getChannel();
FileChannel outputChannel = new FileOutputStream(target).getChannel();) {
int i = 0;
for (long count = inputChannel.size(); count > 0;) {
// long transferTo = outputChannel.transferFrom(inputChannel,
// inputChannel.position(), count);
long transferTo = inputChannel.transferTo(inputChannel.position(), count, outputChannel);
count -= transferTo;
i++;
}
System.out.println("i=" + i);
System.out.println("cost time:" + (System.currentTimeMillis() - start));
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* 方式3 java 标准类库中的Files.copy方法
*
* @param sourcePath
* @param targetPath
*/
private static void copyFileByFilesClass(String sourcePath, String targetPath) {
long start = System.currentTimeMillis();
Path path = Paths.get(sourcePath);
try {
Files.copy(path, new FileOutputStream(new File(targetPath)));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("cost time:" + (System.currentTimeMillis() - start));
}
}