import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
//1將文件中的所有信息,通過合適的IO流讀取出來,封裝成Person對象,使用集合進行存儲
//2將集合對象序列化到另外一個文件persons.txt中
//3從persons.txt反序列化其中的集合,並遍歷集合內容
public class hw4 {
public static void main(String[] args) throws Exception {
BufferedReader br = null; //否則try catch訪問不到
ObjectOutputStream os = null;
ObjectInputStream is = null;
List<Person> list = new ArrayList<>();
try {
String len = "";
int x = 0;
int y = 0;
br = new BufferedReader(new InputStreamReader(new FileInputStream("4a.txt")));
while ((len = br.readLine()) != null) {
String[] strings = len.split(","); //按 , 分割 會有前后兩個字符串
for (int i = 0; i < strings.length; i++) { //strings的長度為2,前面是age,后面是name
x = strings[i].indexOf("="); // indexOf("="):得到"="位置的索引值
len = strings[i].substring(x + 1); // substring(x+1)把"="和其之前的age或name去掉
if (i == 0) { //這一步已經獲取了數據,但傳進Person,還需要規范數據類型
y = Integer.parseInt(len); // Integer.parseInt()是把()里的內容轉換成整數(strings[0]現在是String[]類型)
}
}
Person p = new Person(y, len); //由於age被name覆蓋,所以要用y代替age
list.add(p);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
br.close();
}
}
try {
os = new ObjectOutputStream(new FileOutputStream("Person.txt")); // 將集合對象序列化到另外一個文件persons.txt中
os.writeObject(list); // 將List集合中的對象寫入Person.txt文件中
is = new ObjectInputStream(new FileInputStream("Person.txt")); // 從persons.txt反序列化其中的集合,並遍歷集合內容
List<Person> list1 = (List<Person>) is.readObject(); // 讀取Person.txt中的內容
for (Person p : list1) {
System.out.println(p);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
} finally {
if (is != null) {
}
try {
is.close();
} catch (Exception e3) {
// TODO: handle exception
e3.printStackTrace();
}
}
}
}
}
}
class Person implements Serializable{
//有參 無參構造 set get toString 四個
private int age;
public Person(int age, String name) {
super();
this.age = age;
this.name = name;
}
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}
}