IO之复制文件的四种方式
1. 使用FileStreams复制
这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B。 这是第一个方法的代码:
1 private static void copyFileUsingFileStreams(File source, File dest) 2 throws IOException { 3 InputStream input = null; 4 OutputStream output = null; 5 try { 6 input = new FileInputStream(source); 7 output = new FileOutputStream(dest); 8 byte[] buf = new byte[1024]; 9 int bytesRead; 10 while ((bytesRead = input.read(buf)) > 0) { 11 output.write(buf, 0, bytesRead); 12 } 13 } finally { 14 input.close(); 15 output.close(); 16 } 17
2. 使用FileChannel复制
1 private static void copyFileUsingFileChannels(File source, File dest) throws IOException { 2 FileChannel inputChannel = null; 3 FileChannel outputChannel = null; 4 try { 5 inputChannel = new FileInputStream(source).getChannel(); 6 outputChannel = new FileOutputStream(dest).getChannel(); 7 outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); 8 } finally { 9 inputChannel.close(); 10 outputChannel.close(); 11 } 12 }
3. 使用Commons IO复制
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException { FileUtils.copyFile(source, dest); }
4. 使用Java7的Files类复制
private static void copyFileUsingJava7Files(File source, File dest) throws IOException { Files.copy(source.toPath(), dest.toPath()); }