将Java对象的属性保存到文本文件中,保存的对象为People类型,属性:id、name、age、address。并完成读取出来封装成对象
写出文件
public static void main(String[] args) {
People people = new People(1001,"张三",19,"天津市北辰区");
String data = people.getId()+"#"+people.getName()+"#"+people.getAge()+"#"+people.getAddress();
byte[] buf = data.getBytes();
File file = new File("c:/1.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(buf);
fos.close();
System.out.println("写入成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
读入文件
public static void main(String[] args) {
File file = new File("c:/1.txt");
try {
FileInputStream fis = new FileInputStream(file);
byte[] buf = new byte[100];
int len = fis.read(buf);
String str = new String(buf,0,len);
System.out.println("读取的数据是:"+str);
fis.close();
String[] ss = str.split("#");
for (String s : ss) {
System.out.println(s);
}
People people = new People(Integer.parseInt(ss[0]),ss[1],Integer.parseInt(ss[2]),ss[3]);
System.out.println("对象:"+people);
} catch (IOException e) {
e.printStackTrace();
}
}
读入和写出
public static void main(String[] args) {
People people = new People(1001,"张三",18,"天津市");
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e:/people.txt"));
oos.writeObject(people);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e:/people.txt"));
People people1 = (People) ois.readObject();
System.out.println(people1);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}