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());
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM