【问题标题】:Cannot find text file, can't figure out its path找不到文本文件,无法确定其路径
【发布时间】:2014-08-24 00:33:52
【问题描述】:

我正在运行一个需要读取文本文件并将其保存为字符串的 java 应用程序,但我不断收到 NoSuchFileException。该文本文件位于 src 旁边的名为 assets 的文件夹中。

static String readFile(String path, Charset encoding) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, encoding);
}

这是读取我在这里找到的文件的方法。

try {
    string = readFile("test.txt",Charset.defaultCharset());
} catch (IOException e) {
    e.printStackTrace();
}

我尝试过“/assets/test.txt”和其他变体也无济于事。

【问题讨论】:

  • 如果你运行System.out.println(System.getProperty("user.dir")); 会返回什么?你的文件与用户目录路径的相对路径是什么?
  • 它进入项目工作区并且 test.txt 在 bin 中,所以我将路径更改为 bin/test.txt 并解决了它。谢谢

标签: java eclipse file nosuchfileexception


【解决方案1】:

如果您在 Eclipse 中执行 Java 程序,典型的运行配置会将项目的基本目录作为 Java 进程的当前工作目录。因此,您需要使用基于该目录的相对路径(assets/test.txtsrc/main/assets/test.txt 或类似)。您也可以使用完整路径(例如:/somewhere/workspace/project/assets/test.txt)。

您始终可以使用System.out.println("CWD=" + new File(".").getAbsolutePath()); 来查询 Java 运行时认为它启动的目录。

【讨论】:

    【解决方案2】:

    只需使用(不带斜线):

    try {
      string = readFile("assets/test.txt",Charset.defaultCharset());
    } catch (IOException e) {
      e.printStackTrace();
    }
    

    获取相对于项目根目录的路径。

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多