[JAVA]java複製文件的4種方式

儘管Java提供了一個能夠處理文件的IO操做類。 可是沒有一個複製文件的方法。 複製文件是一個重要的操做,當你的程序必須處理不少文件相關的時候。 然而有幾種方法能夠進行Java文件複製操做,下面列舉出4中最受歡迎的方式。 1. 使用FileStreams複製 這是最經典的方式將一個文件的內容複製到另外一個文件中。 使用FileInputStream讀取文件A的字節,使用FileOutputStream寫入到文件B。 這是第一個方法的代碼: private static void copyFileUsingFileStreams(File source, File dest)         throws IOException {         InputStream input = null;         OutputStream output = null;         try {            input = new FileInputStream(source);            output = new FileOutputStream(dest);                    byte[] buf = new byte[1024];                    int bytesRead;                    while ((bytesRead = input.read(buf)) > 0) {                output.write(buf, 0, bytesRead);            }     } finally {         input.close();         output.close();     } } 正如你所看到的咱們執行幾個讀和寫操做try的數據,因此這應該是一個低效率的,下一個方法咱們將看到新的方式。 2. 使用FileChannel複製 Java NIO包括transferFrom方法,根據文檔應該比文件流複製的速度更快。 這是第二種方法的代碼: private static void copyFileUsingFileChannels(File source, File dest) throws IOException {             FileChannel inputChannel = null;             FileChannel outputChannel = null;         try {         inputChannel = new FileInputStream(source).getChannel();         outputChannel = new FileOutputStream(dest).getChannel();         outputChannel.transferFrom(inputChannel, 0, inputChannel.size());     } finally {         inputChannel.close();         outputChannel.close();     } } 3. 使用Commons IO複製 Apache Commons IO提供拷貝文件方法在其FileUtils類,可用於複製一個文件到另外一個地方。它很是方便使用Apache Commons FileUtils類時,您已經使用您的項目。基本上,這個類使用Java NIO FileChannel內部。 這是第三種方法的代碼: private static void copyFileUsingApacheCommonsIO(File source, File dest)         throws IOException {     FileUtils.copyFile(source, dest); } 4. 使用Java7的Files類複製 若是你有一些經驗在Java 7中你可能會知道,能夠使用複製方法的Files類文件,從一個文件複製到另外一個文件。 這是第四個方法的代碼: private static void copyFileUsingJava7Files(File source, File dest)         throws IOException {             Files.copy(source.toPath(), dest.toPath()); } 
相關文章
相關標籤/搜索