空指针使用PrintWriter的异常

时间:2013-09-26 21:08:40

标签: nullpointerexception printwriter

我有下面的内部类。这是针对客户端/服务器的,我在PrintWriter的“println”中有nullpointer异常。我已经尝试了所有我知道的解决方案,但没有成功。任何人都可以给我一个提示或想法,我必须做什么。谢谢你们!

这是完整的代码:

public class ChatClient extends JFrame{
    private JTextField textToSend;
    private Socket socket;
    private PrintWriter writer
    private String name;
    private JTextArea receivedText;
    private Scanner reader;

    public ChatCliente(String name){
        super("Chat: "+ name);
        this.name = name;
        Font font = new Font("Serif", Font.PLAIN, 20);
        textToSend = new JTextField();
        textToSend.setFont(font);
        JButton btn = new JButton("Send");
        btn.setFont(font);
        btn.addActionListener(new Listener());
        Container content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(BorderLayout.CENTER, textToSend);
        content.add(BorderLayout.EAST, btn);

        receivedText = new JTextArea();
        receivedText.setFont(font);
        JScrollPane scroll = new JScrollPane(receivedText);

        getContentPane().add(BorderLayout.CENTER, scroll);
        getContentPane().add(BorderLayout.SOUTH, content);
        configureNetwork();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,500);
        setVisible(true);
    }

    private void configureNetwork(){
        try{
            socket = new Socket("127.0.0.1",5000);
            writer = new PrintWriter(socket.getOutputStream());
            reader = new Scanner(socket.getInputStream());
            new Thread(new ServerThread()).start();
        }catch (Exception e){}
    }

    private class Listener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            try{
                String s  = name;
                String t = textToSend.getText();
                System.out.println(name+" : "+ textToSend.getText());
                writer.println(s+" : "+t);
                writer.flush();
                textToSend.setText("");
                textToSend.requestFocus();
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }

    private class ServerThread implements Runnable{

        @Override
        public void run() {
           String text;
           try{
               while((text = reader.nextLine()) != null){
                   receivedText.append(text+"\n");
               }
           }catch(Exception e){}
        }
    }
}

2 个答案:

答案 0 :(得分:0)

'name'未声明。

也许你的意思是:

String s  = "name";

答案 1 :(得分:0)

发生在我身上的一些愚蠢的事情:不要在你的文件名中插入“/”,否则它当然会寻找一个可能不存在的额外文件夹。

int number = 1, total = 126;
String path = "some/path/found " + number + "/" + total;
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path, true)));