1、集合到文件
public class ArrayListToFile {
public static void main(String[] args) {
ArrayList<Student> arr = new ArrayList<>();
Student s1 = new Student("001","Tom", 30, "北京");
Student s2 = new Student("002","Ethon", 31, "上海");
Student s3 = new Student("003","Frank", 29, "伦敦");
arr.add(s1);
arr.add(s2);
arr.add(s3);
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("a01.txt"));
for (Student s :arr){
StringBuilder sb = new StringBuilder();
sb.append(s.getSid() + "," + s.getName() + "," + s.getAge() + "," + s.getAddress());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、文件到集合
public class FileToArrayList {
public static void main(String[] args) {
BufferedReader br = null;
ArrayList<Student> stuArr = new ArrayList<>();
try {
br = new BufferedReader(new FileReader("a01.txt"));
String line = null;
while ((line = br.readLine()) != null){
String[] strArr = line.split(",");
Student student = new Student();
student.setSid(strArr[0]);
student.setName(strArr[1]);
student.setAge(Integer.parseInt(strArr[2]));
student.setAddress(strArr[3]);
stuArr.add(student);
}
}catch (IOException e) {
e.printStackTrace();
}finally{
if (br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
for (Student s : stuArr){
String str = s.getSid() + "," + s.getName() + "," + s.getAge() + "," + s.getAddress();
System.out.println(str);
}
}
}