【问题标题】:Cant retrieve file using relative path无法使用相对路径检索文件
【发布时间】:2018-03-10 17:07:45
【问题描述】:

我一直在网上搜索这个看似简单的问题的解决方案,但我总是遇到FileNotFoundException。我在 Eclipse Oxygen 上使用 Java 8,无法从绝对路径或相对路径检索我的 txt 文件。正如其他SO answers 中所建议的那样,我得到了当前目录的路径,我想这是加载 txt 文件的位置:

Path path = FileSystems.getDefault().getPath("").toAbsolutePath();

这显示我的目录为E:\eclipse-java-oxygen-R-win32\HashMap

但是,当我将我的 txt 文件添加到该项目目录(包含 srcbin 目录)时,当我写时仍然找不到该文件:Scanner input = new Scanner(new File("free.txt"))

我什至试过绝对路径:Scanner input = new Scanner(new File("E://eclipse-java-oxygen-R-win32//HashMap//free.txt"));

我在下面附上了我的 free.txt 文件位置的屏幕截图。

您的帮助将不胜感激。

【问题讨论】:

  • 您的路径分隔符可能是问题所在。您是否尝试过使用 / 或 \\.您还可以使用 pathSeparator 常量或 Path API 来摆脱路径分隔符的必要性
  • 我都试过了,但都没有成功
  • 操作系统返回的确切消息是什么?
  • @st4rgut 您遇到了编译问题。尝试运行干净,然后再次构建。似乎您有一个未捕获的已检查异常。
  • 几乎不言自明。用 try catch 块包围您的呼叫并捕获 filenotfoundexception。你有一个编译时问题,因为 java 希望你指定如何处理文件不存在的情况,也许还有更多

标签: java eclipse filenotfoundexception


【解决方案1】:

嗯,让我们试着把事情分开,这样我们就知道到底是什么问题。您还可以尝试通过打印文件异常的确切错误来获得更明确的错误消息。像这样的:

catch (IOException e) { 
      System.out.println("IOException caught -- "); 
      System.out.println(e.getMessage());
    }

但更进一步。您的线路:Scanner input = new Scanner(new File("free.txt"))可以拆分。

试试这个:

String file_name="free.txt";
File file_input = new File(file_name);
if (!file_input.exists())
    abort("FileInput: no such source file: " + file_name);
if (!_file_input.isFile())
    abort("FileInput: can't open a directory: " + file_name);
if (!file_input.canRead())
    abort("FileInput: source file is unreadable: " + file_name);

然后运行

try {
    `Scanner input = new Scanner(file_input)`
catch (FileNotFoundException e) {
        e.printStackTrace();
    }

至少这应该告诉您更多有关错误的信息并为您进行调试。

【讨论】:

    【解决方案2】:

    我不知道您的文件在哪里,但我认为这就是您要查找的内容。我有一个名为 test.json 的文件

    String jsonString = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("test.json").toURI())));
    

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 2019-04-18
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多