【发布时间】:2019-10-28 13:21:39
【问题描述】:
我有一个小问题。当我尝试反序列化 KeyEvent 时,它只发生在一台机器上
我收到此错误:
“java.io.StreamCorruptedException:无效的流标头:AC3F0005
在 java.io.ObjectInputStream.readStreamHeader(Unknown Source)
在 java.io.ObjectInputStream.(未知来源)
在 app.Serializer.deserialize(MyStreamCorruptedException.java:63)"
有一个简单的例子:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
public class MyStreamCorruptedException extends JFrame {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField nameTextField = new JTextField();
frame.add(nameTextField, BorderLayout.NORTH);
KeyListener keyListener = new KeyAdapter() {
public void keyPressed(KeyEvent keyEvent) {
String str = null;
try {
str = serialize(keyEvent);
} catch (IOException e) {
e.printStackTrace();
}
//In reality there is a recording string to the database
//And then its reading from there
try {
Object dStr = deserialize(str);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
nameTextField.addKeyListener(keyListener);
frame.setSize(250, 100);
frame.setVisible(true);
}
public static String serialize(Serializable obj) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
return bos.toString();
}
public static Object deserialize(String str) throws ClassNotFoundException, IOException {
Object obj = null;
if (str != null && !str.isEmpty()) {
ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
}
return obj;
}
}
这是什么问题? 提前致谢!
【问题讨论】:
标签: java swing serialization