简体   繁体   English

如何访问 IDE (eclipse) 中资源文件夹中的数据文件?

[英]How to access data file in resource folder in IDE (eclipse)?

I am doing the Lambdas and Streams Java 8 tutorial.我正在做 Lambdas 和 Streams Java 8 教程。 Instead of adding the data file to the src folder, I created a resources folder in the project and added the data file to it.我没有将数据文件添加到 src 文件夹,而是在项目中创建了一个资源文件夹并将数据文件添加到其中。

Trying to access like this creates a Null Pointer Exception.尝试像这样访问会创建 Null 指针异常。

  private void exercise4() throws IOException, URISyntaxException {
    try (BufferedReader reader = Files.newBufferedReader(
        Paths.get(getClass().getResource(".\\resources\\SonnetI.txt").toURI()), StandardCharsets.UTF_8)) {
      /* YOUR CODE HERE */
    }
  }

This too, gets same error这也得到同样的错误

    Paths.get(getClass().getResource("resources/SonnetI.txt").toURI()), StandardCharsets.UTF_8)) {

I added resources folder to the build path but same error.我将资源文件夹添加到构建路径但同样的错误。

Exception in thread "main" java.lang.NullPointerException
    at lesson2.Lesson2.exercise4(Lesson2.java:96)
    at lesson2.Lesson2.runExercises(Lesson2.java:42)
    at lesson2.Lesson2.main(Lesson2.java:145)

Java 构建路径

日食项目结构

I looked at the other signatures for Paths and this one works!我查看了路径的其他签名, 这个有效!

public static Path get(String first,
                       String... more)
Converts a path string, or a sequence of strings that when joined form a path string, to a Path. If more does not specify any elements then the value of the first parameter is the path string to convert. If more specifies one or more elements then each non-empty string, including first, is considered to be a sequence of name elements (see Path) and is joined to form a path string. The details as to how the Strings are joined is provider specific but typically they will be joined using the name-separator as the separator. For example, if the name separator is "/" and getPath("/foo","bar","gus") is invoked, then the path string "/foo/bar/gus" is converted to a Path. A Path representing an empty path is returned if first is the empty string and more does not contain any non-empty strings.
The Path is obtained by invoking the getPath method of the default FileSystem.

this works fine...这工作正常...

  private void exercise4() throws IOException, URISyntaxException {
    try (BufferedReader reader = Files.newBufferedReader(
        Paths.get("resources","SonnetI.txt"), StandardCharsets.UTF_8)) {
      /* YOUR CODE HERE */
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM