0

I am a beginner in java I am trying to make a communication with serialPort, however at the time of executing the method that receives data it throws me the error.

Exception in thread "Thread-2" java.lang.NullPointerException at Controlador.ControladorMain$4.run(ControladorMain.java:354) at java.lang.Thread.run(Thread.java:748)

I do not understand that it is failing, I have tried the code on another computer and there it does not throw the error I am confused, someone can help me.

public void receiveFile() {
    final InputStream in=serialPort.getInputStream();
    Thread t;
    t = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("listening...: ");

            while (true) {
                FileOutputStream file = null;
                ObjectInputStream out = null;

                try {                        
                    out = new ObjectInputStream(in);

                    if (view.jCheckBoxArchiboR.isSelected()) 
                        file = new FileOutputStream("File.txt");
                    else 
                        file = new FileOutputStream("content.txt");


                    byte[] buf = new byte[1024];

                    while (true) {
                        if (!view.jCheckBoxArchiboR.isSelected())
                           view.jTextAreaBinRecibido.setText(textoABinario(fileRead("content.txt")));

                        int len = out.read(buf);

                        if (len == -1) 
                            break;

                        file.write(buf, 0, len);
                    }
                    if(out.available()<1)
                        sendFile("ack.txt"); 

                } catch (IOException ex) {
                    ex.printStackTrace();
                    System.out.println("An error occurred while receiving the file");

                } finally {
                    try {
                    out.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }
    );
    t.start();
}

line 354 where the error appears is this.

out.close();
  • You should null-check `out` before you try and close it. Because it's in a `finally` block, it gets executed even if the output stream was never successfully instantiated. – khelwood Feb 13 '20 at 23:12
  • oh yes, that was the problem you are absolutely right is coming as null, however it is not clear to me one thing, the program is not supposed to stop at getInputStream () as long as there is no information to read it will not continue with the following lines ? – Rkro98p Feb 13 '20 at 23:51

0 Answers0