java序列化的作用是:方便持久化存储到磁盘,避免程序运行结束后对象就从内存里消失,另外变换成字节序列也更便于网络运输和传播。
List<Test2> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Test2 a = new Test2();
a.setAge(i);
a.setName("名字=" + i);
list.add(a);
}
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("D:\\我的电脑\\asd\\a.txt"));
oos.writeObject(list);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
在java中,可以利用ObjectOutputStream类把对象写入文件中,方便存储
写入的方法也很简单,只需要创建好对象,利用writeObject()方法写入文件中即可。
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("D:\\我的电脑\\asd\\a.txt"));
Object o = ois.readObject();
List<Test2> list = (ArrayList) o;
for (Test2 test : list) {
System.out.println(test);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
取出的时候也只需要利用一个对应的对象存储。
外加一个打印输出流:
{
try {
PrintStream ps = new PrintStream("D:\\我的电脑\\asd\\b.txt");
ps.println("s");
ps.println('a');
ps.println(true);
ps.println(1.12f);
System.out.println("控制台输出");
System.setOut(ps);
System.out.println("输入到文件");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
它可以将所有的类型写入到文件中