我正在做Lambdas和Streams Java 8教程。我没有将数据文件添加到src文件夹中,而是在项目中创建了一个资源文件夹,并将数据文件添加到其中。
尝试这样访问会创建一个空指针异常。
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 */
}
}这也会导致同样的错误
Paths.get(getClass().getResource("resources/SonnetI.txt").toURI()), StandardCharsets.UTF_8)) {我将“资源”文件夹添加到生成路径,但错误相同。
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)


发布于 2020-07-27 15:33:51
我查看了其他签名的路径和这一个工作!
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.这个很好..。
private void exercise4() throws IOException, URISyntaxException {
try (BufferedReader reader = Files.newBufferedReader(
Paths.get("resources","SonnetI.txt"), StandardCharsets.UTF_8)) {
/* YOUR CODE HERE */
}
}https://stackoverflow.com/questions/63116261
复制相似问题