问题描述:

That's my controller:

public class GreetingController implements Controller

{

private static final String MARKERS_FILE_NAME = "markers.txt";

@Override

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception

{

String result = null;

File file = new File(getClass().getResource(MARKERS_FILE_NAME).toURI());

}

}

I have the file markers.txt is in the same level of the controller but incomprehensibly I got a Nullpointer on this line: File file = new File(getClass().getResource(MARKERS_FILE_NAME).toURI());

java.lang.NullPointerException

com.codenvy.example.spring.GreetingController.handleRequest(GreetingController.java:27)

org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)

FYI: I am working with https://codenvy.com/

I also tried

 InputStream in = this.getClass().getClassLoader()

.getResourceAsStream("com/codenvy/example/spring/markers.txt");

BufferedReader br = new BufferedReader(new InputStreamReader(in));

With this result:

java.lang.NullPointerException

java.io.Reader.<init>(Reader.java:78)

java.io.InputStreamReader.<init>(InputStreamReader.java:72)

com.codenvy.example.spring.GreetingController.handleRequest(GreetingController.java:32)

网友答案:

I think you need to specify the path to your file markers.txt relative to the root of the classpath. Since your screen capture shows the package structure, this path is known. Either of the following should work:

InputStream in = this.getClass().getClassLoader()
                .getResourceAsStream("com/codenvy/example/spring/SomeTextFile.txt");

InputStream in = this.getClass()
      .getResourceAsStream("/com/codenvy/example/spring/SomeTextFile.txt");

The snippets above return an InputStream, which hopefully is sufficient for you, assuming you are planning to read the files.

相关阅读:
Top