在 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