访问src文件夹中的一个txt文件

Accessing a txt file in the src folder

我只需要访问一个 txt 文件。我的文件对象构造函数找不到我已经创建并放在 src 文件夹中的 txt 文件。我想避免输入整个文件路径,因为这个项目将在多台计算机之间使用,在这些计算机中,从本地驱动器开始写文件路径是行不通的。给定的图像显示了这种情况。左边是我的文件路径,下面是具体的错误信息,中间是我的代码u到这里。

坦率地说,我只是在寻找要放入 File 构造函数中的内容,而不是更改其外部的代码。但是,我们将不胜感激。

https://i.stack.imgur.com/GoNgZ.png

您想要执行此操作的方法是将文件保存在 src/main/resources 文件夹中,然后使用 ClassPathResource class 找到它。已经 answered here

基本上只需用此替换第 10 行即可获取您的文件(发帖人致谢):

  Resource resource = new ClassPathResource("jsonSchema.json");
  FileInputStream file = new FileInputStream(resource.getFile());

额外:如果您想共享测试文件夹中的文件,请将文件放在 src/test/resources

由于您希望能够 read/write 此文件,因此您应该将其保存在您的代码之外。这意味着您的 BufferedReader 必须从文件系统路径创建。现在有几种方法可以做到这一点,但您最好使用 java.nio API 而不是旧的 java.io.File.

这里主要可以看到3个场景:

  1. 使用工作目录 . 中的相对路径,即从 IDE 调试时项目的位置(不是 src),或者在 jar 旁边制作:
try (BufferedReader br = Files.newBufferedReader(Paths.get("./test.txt"), StandardCharsets.UTF_8)) {
  //Do your stuff
}

或者如果您的文件在 [projectDir]/pingus(仍然不是 src

try (BufferedReader br = Files.newBufferedReader(Paths.get("./pingus/test.txt"), StandardCharsets.UTF_8)) {
  //Do your stuff
}

请注意,这取决于您的应用程序的启动位置,但通常没问题。

  1. 使用从您的代码存储位置生成的绝对路径:

package pingus;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Pongus {

  public static void main(String[] args) throws URISyntaxException, IOException {
    //Find codebase directory
    Path codebase = Paths.get(Pongus.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    Path absdir = codebase.getParent().normalize().toAbsolutePath();
    System.out.println("Working from " + absdir);
    //Path to your file
    Path txtFilePath = absdir.resolve("pingus/test.txt");
    System.out.println("File path " + txtFilePath);
    //Read
    try (BufferedReader rdr = Files.newBufferedReader(txtFilePath, StandardCharsets.UTF_8)) {
      System.out.println("Printing first line:");
      System.out.println("\t" + rdr.readLine());
    }
  }

}

请注意,当 运行 来自 jar 时,这肯定会起作用。它将在使用默认配置的 Eclipse 进行调试期间工作,因为 codebase 最初将指向项目路径中的 bin 子文件夹。它可能不适用于其他 IDE 配置,您编译的 class 可以存储在其他地方

  1. 在您的文件系统上使用绝对路径,硬编码或来自某些配置。
try (BufferedReader rdr = Files.newBufferedReader(Paths.get("C:\mydirs\pingus\test.txt"), StandardCharsets.UTF_8)) {
  //Do your stuff
}