尝试在java中读取txt文件时出现java.lang.NullPointerException

时间:2015-03-31 23:14:56

标签: java file

我不确定为什么我会收到npe,我可以阅读src/main/resources旁边的目录中的其他文件。

它是一个基于maven的项目,运行于eclipse。

任何想法?

Java ..

StringBuilder sb = new StringBuilder();
try {

    InputStream is = ShaderControl.class.getResourceAsStream("fragmentShader.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    String line;
    while ((line = br.readLine()) != null) {

        sb.append(line);
        sb.append('\n');
    }
    is.close();

} catch (Exception e) {
    e.printStackTrace();
}
System.out.println("Shader is " + sb.toString());

控制台输出..

java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:90)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:119)
    at justc0de.engine.tools.ShaderControl.loadShader(ShaderControl.java:36)
    at justc0de.engine.ui.GameRenderer.init(GameRenderer.java:157)
    at jogamp.opengl.GLDrawableHelper.init(GLDrawableHelper.java:640)
    at jogamp.opengl.GLDrawableHelper.init(GLDrawableHelper.java:662)
    at javax.media.opengl.awt.GLCanvas$9.run(GLCanvas.java:1366)
    at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1275)
    at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:1131)
    at javax.media.opengl.awt.GLCanvas$11.run(GLCanvas.java:1394)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:314)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:750)
    at java.awt.EventQueue.access$300(EventQueue.java:115)
    at java.awt.EventQueue$3.run(EventQueue.java:711)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(AccessController.java:311)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:88)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:720)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:254)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:162)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:158)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:103)
Shader is 
Program link error: 

目录列表..

rob@work:~/git/justc0de$ ls src/main/resources/*.txt
src/main/resources/fragmentShader.txt  src/main/resources/vertexShader.txt

1 个答案:

答案 0 :(得分:1)

发现它应该是..

InputStream is = ShaderControl.class.getResourceAsStream("/fragmentShader.txt");