问题是,当我将序列化对象存储在.txt文件中时,它不是可读形式,并且包含一些随机符号和字母.首先,我想知道背后的原因是什么,然后如何解决这个问题.
好的所以这是我的代码:我要序列化的对象
package serialized;
import java.io.Serializable;
import javax.swing.JOptionPane;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
String s_name;
int roll_no;
public Student(String s_name, int roll_no){
this.s_name=s_name;
this.roll_no=roll_no;
}
public void getInfo(){
JOptionPane.showMessageDialog(null, "Name: "+s_name+" Roll No: " + roll_no);
}
}
序列化
package serialized;
import java.io.*;
public class StudentWriter {
public static void main(String[] args) {
Student s1=new Student("Asiya", 58);
try{
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
// Writing Object Info to File
oos.writeObject(s1);
System.out.println("Data has been written to file");
oos.close();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
反序列化
package serialized;
import java.io.*;
public class StudentReader {
public static void main(String[] args) {
try{
FileInputStream fis=new FileInputStream("abc.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
// Reading Data from File
Student s_data=(Student)ois.readObject();
System.out.println("Data has been read");
s_data.getInfo();
ois.close();
fis.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
输出:
?í sr serialized.Student I roll_noL s_namet Ljava/lang/String;xp :t Asiya