集合到文件
需求和思路
代码演示
package Demo1;
import java.sql.PreparedStatement;
/**
* @auther 黄磊
* @2021/8/20 17:00
**/
public class Student {
private String ID;
private String name;
private int age;
private String adress;
public Student() {
}
public Student(String ID, String name, int age, String adress) {
this.ID = ID;
this.name = name;
this.age = age;
this.adress = adress;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
//这个可以写 也可以不写 我是方便测试才写的
@Override
public String toString() {
return "Student{" +
"ID='" + ID + '\'' +
", name='" + name + '\'' +
", age=" + age +
", adress='" + adress + '\'' +
'}';
}
}
package Demo1;
import java.io.*;
import java.util.ArrayList;
/**
* @auther 黄磊
* @2021/8/20 17:03
**/
public class ArrayListToFileDemo {
public static void main(String[] args) throws IOException {
ArrayList<Student> array = new ArrayList<>();
BufferedWriter fw = new BufferedWriter(new FileWriter("Previous\\123.java"));
Student s1 = new Student("itheima001", "林青霞", 30, "西安");
Student s2 = new Student("itheima002", "张曼玉", 35, "武汉");
Student s3 = new Student("itheima003", "王祖贤", 33, "郑州");
array.add(s1);
array.add(s2);
array.add(s3);
for (Student s : array) {
// String info = s.getID() + "," + s.getName() + "," + s.getAge() + "," + s.getAdress();
//此处也可以用StringBuilder方法
StringBuilder sb = new StringBuilder();
String info = sb.append(s.getID()).append(",").append(s.getName()).append(",").
append(s.getAge()).append(",").append(s.getAdress()).toString();
fw.write(info);
fw.newLine();//重要
fw.flush();
}
fw.close();
}
}
效果
会在Previous(相对路径)下创建一个123.java的文件,内容如下
从文件到集合
需求和思路
代码演示
//共用一个Student类
package Demo1;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* @auther 黄磊
* @2021/8/20 17:20
**/
public class FileToArrayListDemo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("Previous\\123.java"));
ArrayList<Student> array = new ArrayList<>();
String Line;
while ((Line = br.readLine()) != null) {
Student s = new Student();
// ss.setID(Line.split(",")[0]);
// ss.setName(Line.split(",")[1]);
// ss.setAge(Integer.parseInt(Line.split(",")[2]));
// ss.setAdress(Line.split(",")[3]);
// array.add(ss);
//代码缺点:4行代码都用split()方法 可以简化代码
String[] split = Line.split(",");
s.setID(split[0]);
s.setName(split[1]);
s.setAge(Integer.parseInt(split[2]));
s.setAdress(split[3]);
array.add(s);
}
for (Student ss : array) {
System.out.println(ss.getID() + "," + ss.getName() + "," + ss.getAge() + "," + ss.getAdress());
}
}
}
结果
在控制台打印集合里面的内容