当我尝试通过套接字发送此类时,我得到的只是 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/