GetResource in Java, URI Based in Codenvy

What is 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 a markers.txt file at the same controller level, but it is not clear that I got 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 work with https://codenvy.com/

enter image description here

I also tried

  InputStream in = this.getClass().getClassLoader()
               .getResourceAsStream("com/codenvy/example/spring/markers.txt");
  BufferedReader br = new BufferedReader(new InputStreamReader(in));

Using 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)
+4
source share
1 answer

I think you need to specify the path to your file markers.txtrelative to the root of the class path. Since your screen capture shows the structure of the package, this path is known. Any 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 excerpts above return InputStreamwhich, I hope, are enough for you if you plan to read files.

0

All Articles