1. 使用FileInputStream
public static void copy(File source, File destination) {
try(FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination)){
byte[] bytes = new byte[2048];
int read;
while ((read = fis.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2. 使用BufferedInputStream处理FileInputStream
public static void copyByBuffer(File source, File destination) {
try(FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);){
byte[] bytes = new byte[2048];
int read;
while ((read = bis.read(bytes)) != -1) {
bos.write(bytes, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
3.使用FileChannel
public static void copyByNio(File source, File destination) {
try(FileChannel fromChannel = new FileInputStream(source).getChannel();
FileChannel toChannel = new FileOutputStream(destination).getChannel();) {
ByteBuffer buffer = ByteBuffer.allocate(2048);
while (fromChannel.read(buffer) != -1) {//不用记录读取个数,buffer的position和limit字段会记录
buffer.flip();//读模式
toChannel.write(buffer);
buffer.clear();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
4. 使用FileChannel的transfer方法
public static void FileCopyNio(File source, File destination) {
try(FileChannel fromChannel = new FileInputStream(source).getChannel();
FileChannel toChannel = new FileOutputStream(destination).getChannel();) {
long count = fromChannel.size();
fromChannel.transferTo(0, count, toChannel);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
5. 使用Apache Commons IO复制
Appache Commons IO 提供了一个FileUtils.copyFile(File from, File to)方法用于文件复制
public static void copyFileByApacheCommonsIO(File source, File destination) throws IOException {
FileUtils.copyFile(source, destination);
}
6. 使用Java7的Files类复制
注意参数是Path对象
public static void copyFileUsingJava7Files(File source, File destination) throws IOException {
Files.copy(source.toPath(), destination.toPath());
}
性能测试……自己写