【问题标题】:Reading the file from the same package从同一个包中读取文件
【发布时间】:2020-05-19 13:53:33
【问题描述】:

我一直在尝试读取我的 java 项目中的文本文件,我整天都在寻找解决方案,我尝试了很多方法,但没有一个奏效。他们中有一些: (另外,我必须使用 File 和 Scanner 类)

String file = "fileTest.txt";
var path = Paths.get("test", file);
System.out.println(path);
System.out.println(Files.readString(path));

线程“主”java.nio.file.NoSuchFileException 中的异常: 测试\fileTest.txt

    URL url = ClassLoader.class.getResource("fileTest.txt");
    File file = null;
    file = new File(url.toURI());
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter(" ");

    while(scanner.hasNext()) {
        System.out.println(scanner.toString());
    }

线程“主”java.lang.NullPointerException 中的异常

    File file = new File("../test/fileTest.txt");
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter(" ");

    while(scanner.hasNext()) {
        System.out.println(scanner.toString());
    }

    scanner.close();

线程“main”java.io.FileNotFoundException中的异常:..\test\fileTest.txt(系统找不到指定的路径)

【问题讨论】:

  • 查看我的回答,了解如何将文件夹作为资源包含在构建路径中。

标签: java


【解决方案1】:

这里的问题是项目结构以及您尝试查找该文件的方式。按照惯例,您的 java 类文件应该存在于目录src/main/java 中,而您的资源文件应该存在于目录src/main/resources 中。如果遵循此约定,则可以通过 ClassLoader 获取资源。

        try (InputStream input = getClass().getClassLoader().getResourceAsStream("test.txt");
             Scanner scanner = new Scanner(Objects.requireNonNull(input)).useDelimiter(" ")) {
            while(scanner.hasNext()) {
                System.out.println(scanner.toString());
            }
        } catch (IOException ioe) {
            throw new RuntimeException("Something went wrong scanning file!", ioe);
        }

【讨论】:

    【解决方案2】:

    所有关于相对路径的答案是否有效取决于您在运行程序时的工作目录。如果您真的希望您的文件存在于类路径中,那么您要做的就是将其用作资源并查看如何在运行时加载资源。另一方面,如果您想像对待任何其他文件一样对待它,如果您希望任何相对路径能够正常工作,或者在某个已知位置指定绝对路径,您将需要知道运行时的工作目录是什么,像一个配置文件。

    【讨论】:

      【解决方案3】:

      使用 BufferReader 读取文件,使用 try-with-resource 在处理终止时自动关闭资源。

      查看有关 Java try-with-resource 的信息:https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

      编辑:确保您已将该文件夹作为资源包含在构建路径中。 How do I add a resources folder to my Java project in Eclipse

      String inputFile = "test/fileTest.txt";
      List<String> lines = new ArrayList<>();
      
      try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {
      
          String line = bufferedReader.readLine();
      
          while(line != null){
              lines.add(line);
              line = bufferedReader.readLine();
          }
      
      } catch (IOException e) {
          e.printStackTrace();
      }
      

      【讨论】:

        【解决方案4】:

        替换

        File file = new File("../test/fileTest.txt");
        Scanner scanner = new Scanner(file);
        

        与

        File file = new File("test/fileTest.txt");
        Scanner scanner = new Scanner(file);
        

        然后,如果您想确认,只需执行以下操作:

        System.out.println(file.exists());
        

        另外,替换

        while(scanner.hasNext()) {
            System.out.println(scanner.toString());
        }
        

        与

        while(scanner.hasNext()) {
            System.out.println(scanner.next());
        }
        

        因为scanner.toString()不能用于获取输入;应该是scanner.next()。

        【讨论】:

        • 我也试过了,线程“main”java.io.FileNotFoundException中的异常:test\fileTest.txt(系统找不到指定的文件)
        • @curiousStudents - 再试一次。我敢肯定,您在上次尝试中一定犯了其他错误。我在发布答案之前测试了我的代码。
        • @curiousStudents - 你还没有将scanner.toString() 替换为scanner.next()。另外,您确定您的文件名具有.txt 扩展名吗?我建议你将文件的内容备份到某个地方,删除文件并在此位置创建一个新文件fileTest.txt,然后从备份中恢复内容。
        • 是的,谢谢,我创建了一个文本文件,但它不是以 .txt 扩展名保存的,而是作为“文件”保存的
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-07
        • 2011-04-01
        • 1970-01-01
        • 2013-05-09
        • 2013-07-12
        相关资源
        最近更新 更多