I am doing the Lambdas and Streams Java 8 tutorial. 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.
Trying to access like this creates a Null Pointer Exception.
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)
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 */
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.