【问题标题】:InputStreamReader NullPointerExceptionInputStreamReader NullPointerException
【发布时间】:2017-07-23 22:48:14
【问题描述】:

以下代码有时会出现 NullPointerException 的原因是什么。

BufferedReader reader = new BufferedReader(new InputStreamReader
                    (getClass().getClassLoader().getResourceAsStream(this.getClientHost()+".txt")));

奇怪的是,它有时无异常地工作,但有时会出现此异常。我的代码我试图多次读取该文件。通常,它第一次读取成功,而在第二次尝试中它给出了这个异常。

这里是所有代码:

public class DictionaryImp extends RemoteServer implements Dictionary {
static FileOutputStream log;
    public DictionaryImp(){
        super();        
    }
public String statictics() {
        // TODO Auto-generated method stub
        try {
            setLog("Statistic", this.getClientHost());
        } catch (ServerNotActiveException e1) {
            // TODO Auto-generated catch block
            System.err.println("server is not active!!");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       //some statistic    

        return msg;
    }

public String log() throws RemoteException {

        try {
            setLog("Log", this.getClientHost());
        } catch (ServerNotActiveException e1) {
            // TODO Auto-generated catch block
            System.err.println("Client is not active!!");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String msg = "";
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader
                    (getClass().getClassLoader().getResourceAsStream(this.getClientHost()+".txt")));
            String line = null;

            while((line = reader.readLine()) != null){
                msg += line + "\n";
            }
            reader.close();
        } catch (ServerNotActiveException | IOException e) {
            // TODO Auto-generated catch block
            System.err.println("Client is not active");
        }

        return msg;
    }

private static void  createLogFile(String logFileName){
        File logFile = null;
        logFile = new File(logFileName);

        if(!logFile.exists())
            try {
                logFile.createNewFile();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                System.err.println("Log file couldn't created!!");
            }
        try {
            log = new FileOutputStream(logFile, true);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            System.err.println("Log file not found!!");
        }       
    }

    private static void setLog(String event, String ip) throws IOException{
        createLogFile("Resources/"+ip+".txt");
        String time = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(Calendar.getInstance().getTime());
        String msg = ip + "\t " +event + "\t " + time + "\n";
        try {
            log.write(msg.getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.err.println("Log file not found!!");
        }
        log.close();
    }
}

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Unknown Source)
    at java.io.InputStreamReader.<init>(Unknown Source)
    at DictionaryImp.search(DictionaryImp.java:79)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
    at sun.rmi.transport.Transport$1.run(Unknown Source)
    at sun.rmi.transport.Transport$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Unknown Source)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
    at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
    at sun.rmi.server.UnicastRef.invoke(Unknown Source)
    at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(Unknown Source)
    at java.rmi.server.RemoteObjectInvocationHandler.invoke(Unknown Source)
    at com.sun.proxy.$Proxy0.search(Unknown Source)
    at ClientRMI.calcThroughput(ClientRMI.java:200)
    at ClientRMI.main(ClientRMI.java:65)

【问题讨论】:

  • 您是否每次都以完全相同的方式运行代码? IE。来自相同目录的相同类路径参数?
  • getClass().getClassLoader().getResourceAsStream("dictionary.txt")
  • 是的代码在运行时尝试多次获取文件。在第一次读取时,它会给出 NPE。有时直接给NPE
  • 我已经回答过了。您自己创建的文件不是您可以通过类加载器加载的资源。

标签: java nullpointerexception inputstream


【解决方案1】:

因为您尝试读取的资源 (dictionary.txt) 不在根目录下的类路径中并且正在解析 null

【讨论】:

  • 呃等等,如果该文件不在根目录下而是在同一个路径层次结构中怎么办?例如,您运行 foo.bar.Baz 并且资源位于 /foo/bar/dictionary.txt?
  • 是类路径根目录上的foo 吗?
  • 嗯,是的...你在这门课上跑步,所以它必须是,对吧?要么那个,要么我不明白你的问题
  • @fge 看到这需要相对路径stackoverflow.com/questions/6608795/…
  • 不,它在类路径中。正如我所说,它有时会毫无例外地阅读。
【解决方案2】:

您正在访问一个找不到的资源,请尝试用以下代码说明它:

    InputStream is = getClass().getClassLoader().getResourceAsStream("dictionary.txt");

    System.out.println(is == null);

【讨论】:

  • 正如我在第一次尝试读取它找到的文件时所说,在第二次尝试中它返回 null
  • 请提供所有访问资源的代码sn-ps。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
  • 2011-12-20
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
相关资源
最近更新 更多