读取文本文件中Student.txt中内容(编号,姓名,成绩)存放到学生对象中,并添加到集合对象,然后将分数低于等于80分的学生输出到另外一个文件中
程序员文章站
2024-03-04 11:26:11
...
读取文本文件中Student.txt中内容(编号,姓名,成绩)存放到学生对象中,并添加到集合,然后将分数低于等于80分的学生输出到另外一个文件中
大概说一下,这里面加上main函数一共有addlist()、outgrade()、creatstu()4个方法。
其中addlist为读取文件内容,然后赋值给学生对象并将学生对象添加到集合。
outgrade 方法为将成绩低于等于80分的学生输出到另外一个文件里。
creatstu为创建一个学生对象
读写文件中的路径我也没有删除,如果谁需要的话定义两个文件路径就可以了。
附上两个文件的图片,介绍写的有点乱,谁需要的话就得稍微费点点时间了,大家共同学习,共同进步。加油加油加油!
“`
package Demo2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Listdemo {
public static void main(String[] args) throws IOException {
addlist();
outgrade();
}
public static List<Student> list = new ArrayList<Student>();
public static void addlist() {
File file = new File("C:\\Users\\Administrator\\Desktop\\abcde - 副本.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String str = null;
while ((str = br.readLine()) != null) {
String[] arr = str.split(",");
Student stu = null;
for (int i = 0; i < arr.length; i++) {
stu = creatstu();
stu.setStuID(Integer.parseInt(arr[0]));
stu.setName(arr[1]);
stu.setAge(Integer.parseInt(arr[2]));
stu.setGrade(Integer.parseInt(arr[3]));
}
list.add(stu);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (Student student : list) {
System.out.println(student);
}
}
public static Student creatstu() {
Student stu = new Student();
return stu;
}
public static void outgrade() throws IOException {
File file1 = new File("C:\\Users\\Administrator\\Desktop\\123.txt");
BufferedWriter br1 = null;
br1 = new BufferedWriter(new FileWriter(file1));
for (Student student : list) {
if (student.getGrade() <= 80) {
br1.write(student.getStuID() + "," + student.getName() + "," + student.getAge() + ","
+ student.getGrade());
br1.flush();
br1.newLine();
}
System.out.println(student);
}
br1.close();
}
}