参考地址:
1. http://blog.csdn.net/yczz/article/details/38761237
File类
ObjectInputStream && ObjectOutputStream, 该流允许读取或写入用户自定义的类,但被读取或写入的类必须实现了Serializable接口 DataInputStream && DataOutputStream 有时没有必要存储整个对象的信息,而只是要存储一个对象的成员数据,成员数据的类型假设都是Java的基本数据类型,这样的需求不必使用到与Object输入、输出相关的流对象,可以使用DataInputStream、DataOutputStream来写入或读出数据
打算将Member类实例的成员数据写入文件中,并打算在读入文件数据后,将这些数据还原为Member对象。下面的代码简单示范了如何实现这个需求
package com.hxw.io; class Student implements Serializable{
private String name;
private int age; public Student(String name, int age) {
super();
this.name = name;
this.age = age;
} @Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
} } import java.io.*;
public class ObjetStream {
public static void main(String[] args) {
ObjectOutputStream objectwriter = null;
ObjectInputStream objectreader = null; try {
objectwriter = new ObjectOutputStream(new FileOutputStream("D:/David/Java/java 高级进阶/files/student.txt"));
objectwriter.writeObject(new Student("gg", 22));
objectwriter.writeObject(new Student("tt", 18));
objectwriter.writeObject(new Student("rr", 17)); objectreader=new ObjectInputStream(new FileInputStream("D:/David/Java/java 高级进阶/files/student.txt"));
for (int i = 0; i < 3; i++) {
System.out.println(objectreader.readObject());
}
} catch (IOException | ClassNotFoundException e) {
// TODO自动生成的 catch 块
e.printStackTrace();
}finally{
try {
objectreader.close();
objectwriter.close();
} catch (IOException e) {
// TODO自动生成的 catch 块
e.printStackTrace();
}
}
}
}
package com.hxw;
public class Member {
private String name;
private int age;
public Member() {
}
public Member(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
} import java.io.*;
public class DataStreamDemo
{
public static void main(String[]args)
{
Member[] members = {new Member("Justin",90),
new Member("momor",95),
new Member("Bush",88)};
try {
DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(args[0])); for(Member member:members)
{
//写入UTF字符串
dataOutputStream.writeUTF(member.getName());
//写入int数据
dataOutputStream.writeInt(member.getAge());
} //所有数据至目的地
dataOutputStream.flush();
//关闭流
dataOutputStream.close(); DataInputStream dataInputStream = new DataInputStream(new FileInputStream(args[0])); //读出数据并还原为对象
for(int i=0;i<members.length;i++)
{
//读出UTF字符串
String name =dataInputStream.readUTF();
//读出int数据
int score =dataInputStream.readInt();
members[i] = new Member(name,score);
} //关闭流
dataInputStream.close(); //显示还原后的数据
for(Member member : members)
{
System.out.printf("%s\t%d%n",member.getName(),member.getAge());
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}