您好,欢迎来到爱玩科技网。
搜索
您的当前位置:首页Java读写txt文件

Java读写txt文件

来源:爱玩科技网

结果:

大致思路:
一次读一行, 使用BufferedReaderreadLine(), 然后利用中间的空格来截取, 分段读取到变量:

        // 从文本文件中读,将读出的数据存放于集合中
        List<Student> list = new ArrayList<>();

        File file = new File(fileName);
        try {
            BufferedReader bf = new BufferedReader(new FileReader(file));

            String content = "";

            while (content != null) {
                content = bf.readLine();

                if (content == null) {
                    break;
                }
                // 设置正则将多余空格或Tab键都转为一个空格
                String[] str = content.trim().split("\\s{2,}|\t");
                Student student = new Student();

                student.setId(str[0]);
                student.setName(str[1]);
                student.setGender(str[2]);
                student.setJava(Float.parseFloat(str[3]));
                student.setEnglish(Float.parseFloat(str[4]));
                student.setMath(Float.parseFloat(str[5]));
                student.setTotalScore();
                student.setAverage();

                list.add(student);
            }

            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

写入txt文件

思路: 使用打印流PrintStreamprintf()格式化输出.

    // 将集合中的数据写入到txt文件中, 思路: 使用打印流
    public void WriteTxt(List<Student> list, String fileName) {
        try {
            PrintStream printStream = new PrintStream(new FileOutputStream(fileName));
            printStream.printf("学号\t姓名\t性别\t总分\t平均分\n");
            for (int i = 0; i < list.size(); i++) {
                printStream.printf("%s\t%s\t%s\t%.2f\t%.2f\n", list.get(i).getId(),
                    list.get(i).getName(), list.get(i).getGender(),
                        list.get(i).getTotalScore(), list.get(i).getAverage());
            }
            printStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- aiwanbo.com 版权所有 赣ICP备2024042808号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务