如何使用io流实现读写文件模拟数据库的连接与提交!

文件工具类

package util;

import pojo.Course;
import pojo.DataItem;
import pojo.Selection;
import pojo.Student;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Magic
 * @version 1.0
 */
public class FileUtil {
    /**
     * 删除文件
     * @param filePath 要删除的文件路径
     */
    public static void deleteDataFile(String filePath) {
        File file = new File(filePath);
        System.out.println();
        if (!file.exists()) {
            System.out.println("文件不存在无法删除文件");
            return;
        }
        if (file.delete()) {
            System.out.println("文件已删除");
        }
    }


    /**
     * 保存数据文件
     * @param filePath 保存数据文件路径
     * @param dataList 保存数据
     */
    public static void saveDataToFile(String filePath, List dataList) {
        System.out.println("开始导入数据到文件");
        try (FileWriter writer = new FileWriter(filePath)) {
            for (DataItem item : dataList) {
                writer.write(item.toString());
                writer.write(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("导入成功");
    }

    /**
     * 读取student.dat文件
     * @return 返回更新后的student集合
     */
    public static List readStudentFile() {
        String filePath = "src/file/student.dat";
        // 创建用于存储数据的集合
        List studentList = new ArrayList<>();
        // 创建用于读取文件的BufferedReader对象
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = reader.readLine()) != null) {
                // 在这里解析每行数据并创建数据对象,然后将其添加到studentList中
                // 按空格分隔并创建学生对象
                String[] parts = line.split("\t");
                if (parts.length == 4) {
                    String id = parts[0];
                    String lastName = parts[1];
                    int age = Integer.parseInt(parts[2]);
                    String gender = parts[3];
                    Student student = new Student(id, lastName, age, gender);
                    studentList.add(student);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            //关闭流防止资源泄露
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return studentList;
    }

    /**
     * 读取sc.dat文件
     * @return 返回更新后的selection集合
     */
    public static List readSelectionFile() {
        String filePath = "src/file/sc.dat";
        // 创建用于存储数据的集合
        List selectionList = new ArrayList<>();
        // 创建用于读取文件的BufferedReader对象
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = reader.readLine()) != null) {
                // 在这里解析每行数据并创建数据对象,然后将其添加到selectionList中
                // 按空格分隔并创建选课对象
                String[] parts = line.split("\t");
                if (parts.length == 3) {
                    String studentId = parts[0];
                    String courseId = parts[1];
                    int score = Integer.parseInt(parts[2]);
                    Selection selection = new Selection(studentId, courseId, score);
                    selectionList.add(selection);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            //关闭流防止资源泄露
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return selectionList;
    }

    /**
     * 读取course.dat文件
     * @return 返回更新后的course集合
     */
    public static List readCourseFile() {
        String filePath = "src/file/course.dat";
        // 创建用于存储数据的集合
        List courseList = new ArrayList<>();
        // 创建用于读取文件的BufferedReader对象
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = reader.readLine()) != null) {
                // 在这里解析每行数据并创建数据对象,然后将其添加到courseList中
                // 按空格分隔并创建课程对象
                String[] parts = line.split("\t");
                if (parts.length == 5) {
                    String courseId = parts[0];
                    String courseName = parts[1];
                    int credit = Integer.parseInt(parts[2]);
                    int hours = Integer.parseInt(parts[3]);
                    String nature = parts[4];
                    Course course = new Course(courseId, courseName, credit, hours, nature);
                    courseList.add(course);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            //关闭流防止资源泄露
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return courseList;
    }
}

实体类

Course

package pojo;

 public class Course extends DataItem {
    private String courseId;
    private String courseName;
    private int credit;
    private int hours;
    private String nature;

    public Course() {
    }

    public Course(String courseId, String courseName, int credit, int hours, String nature) {
        this.courseId = courseId;
        this.courseName = courseName;
        this.credit = credit;
        this.hours = hours;
        this.nature = nature;
    }

    // 构造函数、getter和setter方法


    @Override
    public String toString() {
        return courseId + "\t" + courseName + "\t" + hours + "\t" + credit + "\t" + nature;
    }

    /**
     * 获取
     * @return courseId
     */
    public String getCourseId() {
        return courseId;
    }

    /**
     * 设置
     * @param courseId
     */
    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    /**
     * 获取
     * @return courseName
     */
    public String getCourseName() {
        return courseName;
    }

    /**
     * 设置
     * @param courseName
     */
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    /**
     * 获取
     * @return credit
     */
    public int getCredit() {
        return credit;
    }

    /**
     * 设置
     * @param credit
     */
    public void setCredit(int credit) {
        this.credit = credit;
    }

    /**
     * 获取
     * @return hours
     */
    public int getHours() {
        return hours;
    }

    /**
     * 设置
     * @param hours
     */
    public void setHours(int hours) {
        this.hours = hours;
    }

    /**
     * 获取
     * @return nature
     */
    public String getNature() {
        return nature;
    }

    /**
     * 设置
     * @param nature
     */
    public void setNature(String nature) {
        this.nature = nature;
    }
}

数据输出类

package pojo;

public abstract class DataItem {

}

读取文件模拟数据库连接

// 读取数据库文件数据
        // 学生数据
        List studentList = FileUtil.readStudentFile();
        // 课程数据
        List courseList = FileUtil.readCourseFile();
        // 选课数据
        List selectionList = FileUtil.readSelectionFile();

刷新文件实现模拟数据库的提交

//刷新数据库文件数据
        //先删除文件
        FileUtil.deleteDataFile("src/file/student.dat");
        FileUtil.deleteDataFile("src/file/course.dat");
        FileUtil.deleteDataFile("src/file/sc.dat");
        //后保存数据到文件实现刷新
        FileUtil.saveDataToFile("src/file/student.dat", studentList);
        FileUtil.saveDataToFile("src/file/course.dat", courseList);
        FileUtil.saveDataToFile("src/file/sc.dat", selectionList);

你可能感兴趣的:(数据库,windows,java)