使用BufferedReader和BufferedWriter实现对文件信息的增删改查
package dao.impl; import dao.IStudentDao; import entity.Student; import java.io.*; import java.util.ArrayList; import java.util.List; /** * @Author: hyy * @Date: 2020/12/9 16:55 */ public class IStudentDaoImpl implements IStudentDao { /** * 根据id和课程编号进行 选课 * @param student * @return * @throws IOException */ @Override public boolean insertCourse(Student student) throws IOException { BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter("UniversitySelectCourseSystem\\SelectCourse.txt",true)); bufferedWriter.write(student.getId()+","+student.getStudentName()+","+student.getCourseName()+","+student.getSerialNumber()); bufferedWriter.newLine(); bufferedWriter.close(); return false; } /** * 根据id和课程编号进行 退课 * @param id * @param serialNumber * @return * @throws IOException */ @Override public boolean deleteCourse(Integer id,String serialNumber) throws IOException { BufferedReader bufferedReader=new BufferedReader(new FileReader("UniversitySelectCourseSystem\\SelectCourse.txt")); List<Student> studentList=new ArrayList<>(); String string ; while ((string=bufferedReader.readLine())!=null){ String[] dates=string.split(","); Student student=new Student(Integer.parseInt(dates[0]),dates[1],dates[2],dates[3]); System.out.println(student.toString()); studentList.add(student); } for (int i = 0; i < studentList.size(); i++) { Student student=studentList.get(i); if (student.getSerialNumber().equals(serialNumber)){ studentList.remove(i); } } BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter("UniversitySelectCourseSystem\\SelectCourse.txt")); for (int i = 0; i < studentList.size(); i++) { Student student=studentList.get(i); String returnString=String.format("%s,%s,%s,%s",student.getId(),student.getStudentName(),student.getCourseName(),student.getSerialNumber()); bufferedWriter.write(returnString); bufferedWriter.newLine(); } bufferedReader.close(); bufferedWriter.close(); return false; } /** * 根据id 查询已选课程 * @param id // * @param serialNumber * @return boolean * @throws IOException */ @Override public boolean selectCourse(Integer id) throws IOException { BufferedReader bufferedReader=new BufferedReader(new FileReader("UniversitySelectCourseSystem\\SelectCourse.txt")); String string; List<Student> studentList=new ArrayList<>(); while ((string=bufferedReader.readLine())!=null){ String []dates=string.split(","); Student student=new Student(Integer.parseInt(dates[0]),dates[1],dates[2],dates[3]); System.out.println(student.toString()); studentList.add(student); } for (int i = 0; i < studentList.size(); i++) { Student student=studentList.get(i); if (student.getId().equals(id)){ System.out.println(student.toString()); } } return false; } }