Java InputStreamReader NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22431392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:40:06  来源:igfitidea点击:

InputStreamReader NullPointerException

javanullpointerexceptioninputstream

提问by user1914367

What can it be the reason to get NullPointerException sometimes with below code piece.

有时使用以下代码段获得 NullPointerException 的原因是什么。

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

The strange part that it sometimes works without exception but sometimes give this exception. My code i trying to read that file many times. Generally it reads in first time successful and in the second attempt it gives this exception.

奇怪的部分是它有时无一例外地工作,但有时却给出了这个例外。我的代码试图多次读取该文件。通常它第一次成功读取,第二次尝试时它给出了这个异常。

Here is all code:

这是所有代码:

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.run(Unknown Source)
    at sun.rmi.transport.Transport.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)

回答by Jigar Joshi

because resource you are attempting to read (dictionary.txt)is not in classpath at the root and being resolved null

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

回答by oschlueter

You're accessing a Resource that couldn't be found, try to illustrate it with this code:

您正在访问无法找到的资源,请尝试使用以下代码对其进行说明:

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

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