在 Java 中複製檔案

Haider Ali 2023年10月12日
  1. Java 複製檔案時的異常處理
  2. Java 複製檔案的示例程式碼
在 Java 中複製檔案

在本文中,我們將介紹將檔案從一個位置複製到另一個位置的方法。在 Java 語言中,有一些庫允許我們將一個檔案移動到另一個目錄。讓我們更深入地瞭解一下。

通過 java 程式碼複製檔案涉及將源路徑和目標路徑儲存在兩個不同的字串中。稍後,我們通過源路徑捕獲所需的檔案併為目標位置建立其副本。你需要新增此庫才能使以下程式碼正常工作。

import static java.nio.file.StandardCopyOption.*;

以下是你需要處理的一些例外情況。

Java 複製檔案時的異常處理

以下是可能對你有用的三個異常處理關鍵字。

  • 如果你遇到檔案已經在目標位置(同名)的情況,你應該使用 REPLACE_EXISTING。這將替換已經存在的檔案。
  • COPY_ATTRIBUTES,這個保留的關鍵字將複製與原始檔連結的屬性。
  • 如果你不想跟隨符號連結,這意味著你不想複製目標連結,你可以使用 NOFOLLOW_LINKS

Java 複製檔案的示例程式碼

import static java.nio.file.StandardCopyOption.*;

import java.io.*;
import java.nio.file.Files;
public class Main {
  public static void main(String[] args) {
    String sourcePath = "E:\\source location\\delftstack.txt"; // source file path
    String destinationPath = "E:\\destination location\\"; // destination file path
    File sourceFile = new File(sourcePath); // Creating A Source File
    File destinationFile = new File(
        destinationPath + sourceFile.getName()); // Creating A Destination File. Name stays the same
                                                 // this way, referring to getName()
    try {
      Files.copy(sourceFile.toPath(), destinationFile.toPath(), REPLACE_EXISTING);
      // Static Methods To Copy Copy source path to destination path
    } catch (Exception e) {
      System.out.println(e); // printing in case of error.
    }
  }
}

在上面的程式碼示例中,如你所見,它新增了庫。我們複製了源路徑,將其儲存在字串 sourcepath 中,並對目標位置執行相同操作。

後來,我們建立了一個原始檔(檔案物件),並將其傳遞給源路徑的字串。現在,我們知道雖然我們通常複製和貼上檔案,但名稱保持不變。為此,我們對原始檔使用 getName()

通過使用 Files.copy(source, target, REPLACE_EXISTING); 命令並傳遞值,我們在上面的程式碼示例中我們在 Java 中複製了一個文字檔案。

作者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相關文章 - Java File