默认是GBK的编码格式,可以调成UTF-8的格式,方法是:
Windows—preferences—General—Workspace—text for encoding
改成UTF-8即可
1、将eclipse默认编码格式改变特别注意的一点是,你以前用默认编码格式的所有项目的中文将会全部乱码,如果再切换成GBK也是没有作用的
2、使用序列化将对象进行储存成文件格式,是一种二进制编码储存,所以你打开储存的txt文件,打开是中文乱码的,这点初学者是最想不通的一点,甚至会和我一样傻逼的看看能不能用用转换编码试试,就是用fileoutputstreamwriter进行编码转换,但还是没有理解这些流类的层级关系,序列化对象使用的ObjectOutputstream是字节输出流,是Outputstream的一个子类,而fileoutputstreamwriter是字符流Writer的一个子类,这两者不能混了。
3、所以就需要反序列化将你序列化的对象进行输出到控制台给大家看
package test2;
import java.io.Serializable;
/*
* 学生类
*/
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private int age;
private String sex;
private String address;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String id, String name, int age, String sex, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.address = address;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "编号:" +this.getId() +"\t" + "姓名:" +this.getName() +"\t" + "年龄:" + this.getAge()+"\t" + "性别:" +this.getSex()+ "\t" +
"地址"+this.getAddress();
}
}
public class Test {
public static void main(String[] args) {
//集合储存学生信息
List<Student> list =new ArrayList<Student>();
//添加2个学员到集合中
list.add(new Student("101", "张三", 20, "男", "深圳福田"));
list.add(new Student("102", "李四", 23, "男", "深圳龙岗"));
list.add(new Student("103", "王五", 22, "女", "深圳宝安"));
//序列化集合对象储存学生信息
ObjectOutputStream oos=null;
try {
oos=new ObjectOutputStream(new FileOutputStream("src//test2//test.txt"));
// System.out.println(stu);
oos.writeObject(list);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
将刚才序列化的集合对象通过反序列化显示在控制台
ObjectInputStream ois=null;
//反序列化显示集合中信息,得到新的集合
ois=new ObjectInputStream(new FileInputStream("src//test2//test.txt"));
@SuppressWarnings("unchecked")
ArrayList<Student> list2=(ArrayList<Student>) ois.readObject();
//遍历集合
for (int i = 0; i < list2.size(); i++) {
Student stu=list.get(i);
System.out.println(stu);
}