简体   繁体   中英

getResource in Java based in the URI in Codenvy

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.

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.

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