写入文档、并读取文档
class Man implements java.io.Serializable{
private int id;
private String name;
private String gender;
public Man(){
}
public Man(int id, String name, String gender) {
super();
this.id = id;
this.name = name;
this.gender = gender;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Man [id=" + id + ", name=" + name + ", gender=" + gender + "]";
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class ManTest {
public static void write(Man m){
OutputStream out = null;
ObjectOutputStream objOut = null;
try {
out = new FileOutputStream("obj.txt");
objOut = new ObjectOutputStream(out);
objOut.writeObject(m);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
objOut.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
write(new Man(1,"张三","男"));
}
}
//读取
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class ManTest {
public static Man read(){
Man m = null;
InputStream in = null;
ObjectInputStream objIn = null;
try {
in = new FileInputStream("obj.txt");
objIn = new ObjectInputStream(in);
m = (Man)objIn.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
objIn.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return m;
}
public static void main(String[] args){
Man m = read();
System.out.println(m);
}
}