Java中的getResource基于Codenvy中的URI

时间:2016-06-30 12:16:14

标签: java codenvy

那是我的控制者:

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());
       }
}

我有文件markers.txt与控制器处于同一级别但不可理解的是我在这一行上有一个Nullpointer: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)

仅供参考:我正在使用https://codenvy.com/

enter image description here

我也试过

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

结果如下:

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)

1 个答案:

答案 0 :(得分:0)

我认为您需要指定文件markers.txt relative 的路径到类路径的根目录。由于您的屏幕截图显示了包结构,因此该路径是已知的。以下任何一种都应该有效:

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

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

上面的代码段返回InputStream,假设您计划阅读文件,这对您来说已经足够了。