- 复制上例中的Student类到本项目中;
- 在项目目录下创建文件name.txt,并写入以下内容:
it001,武松,男,22
it002,林冲,男,20
it003,卢俊义,男,18
it004,石宝,男,23 - 创建MainApp类,包含main()方法
- 在main()方法中:
- 定义一个存储Student对象的集合;
- 循环从文件中读取数据,每次读取一行,并解析每个属性值,封装到一个Student对象中,并将这个对象封装到集合中。
- 遍历集合,找到要修改的“卢俊义”,并将姓名修改为:“史文恭”。
同时将数据再次写回到文件中。 程序结束后,验证文件中的数据是否修改成功。 ```java package Day10.Demo03;/*
@create 2020—11—26—18:26 */
public class Student { private String id; private String name; private String sex; private String age;
public Student() {
}
public Student(String id, String name, String sex, String age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age='" + age + '\'' +
'}';
}
}
```java
package Day10.Demo03;/*
@create 2020--11--26--19:05
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
public class MainApp {
public static void main(String[] args) throws Exception{
BufferedWriter f = new BufferedWriter(new FileWriter("name.txt"));
f.write("it001,武松,男,22\n");
f.write("it002,林冲,男,20\n");
f.write("it003,卢俊义,男,18\n");
f.write("it004,石宝,男,23\n");
f.close();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
ArrayList<String> arr = new ArrayList<>();
char[] chs = new char[14];
int len;
while ((len = br.read(chs)) != -1) {
arr.add(new String(chs));
System.out.println(new String(chs,0,len));
}
System.out.println(arr.get(0));
ArrayList<Student> students = new ArrayList<>();
for (int i = 0; i < arr.size()-1; i++) {
String[] s = String.valueOf(arr.get(i)).replace("\n","").split(",");
System.out.println(Arrays.toString(s));
students.add(new Student(s[0], s[1], s[2], s[3]));
}
for (Student student : students) {
if ("卢俊义".equals(student.getName())) {
student.setName("史文恭");
}
}
for (Student student : students) {
System.out.println(student);
}
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("name.txt"));
for (Student student : students) {
String s = student.getId()+","+student.getName()+","+student.getSex()+","+student.getAge()+"\n";
bufferedWriter.write(s);
}
bufferedWriter.close();
br.close();
}
}