java - 使 JTextArea 可序列化

标签 java sockets nullpointerexception jtextarea serializable

当我尝试通过套接字发送此类时,我得到的只是 NullPointEreException。我该如何做才能不出现空指针异常?

public class Hick implements Serializable{
public JTextArea jta;
public Hick(){
jta = new JTextArea();
}
}

最佳答案

我用下面的代码测试了它,它似乎工作正常......

我会确保您可以首先在本地序列化对象,以排除任何潜在的问题。如果您仍然无法通过套接字加载它,那么您的套接字代码有问题,而不是序列化问题

public class TestSerialisation {

    public static void main(String[] args) {
        new TestSerialisation();
    }

    public TestSerialisation() {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        Wrapper out = new Wrapper();
        System.out.println("Before = " + out.dump());
        try {
            try {
                oos = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
                oos.writeObject(out);
            } finally {
                try {
                    oos.close();
                } catch (Exception e) {
                }
            }

            Wrapper in = null;
            try {
                ois = new ObjectInputStream(new FileInputStream(new File("Test.out")));
                in = (Wrapper) ois.readObject();
            } finally {
                try {
                    ois.close();
                } catch (Exception e) {
                }
            }            
            System.out.println("After = " + (in == null ? "null" : in.dump()));            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public static class Wrapper implements Serializable {

        private JTextArea textArea;

        public Wrapper() {
            textArea = new JTextArea("I'm some text");
        }

        public String dump() {
            return textArea.getText();
        }
    }
}

还要确保您运行的是兼容版本的 Java,并且(如果我没记错的话)两端都有兼容版本的序列化对象。

关于java - 使 JTextArea 可序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13328855/

相关文章:

java - 将 HttpServletRequest 注入(inject) Controller

java - sql.date 与 util.date

java - 无法实例化服务 - Java.NullPointerException

java - 访问构造函数时出现 NullPointerException

java - 什么是NullPointerException,我该如何解决?

java - 如何从 FileItem 获取完整路径

java - 以编程方式创建 MP3

sockets - 无法在 Windows 8 Metro 风格应用程序中使用 IPAddress 或类似类型

c++ - 无法按 NULL 字节 (\0) 拆分

python - 使用现有的异步事件循环在 Python 中实现 REST API