Java读写txt文件

格式化数据.png
我用一个Student实体类作为存储容器:
JavaBean.png

结果:
读取txt文件.png

大致思路:
一次读一行, 使用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();
        }

    }

如需要, 完整代码下载地址:
https://github.com/menglanyingfei/Java/blob/master/CodeCollection/JavaSEProjects/excelIo/excelIo.zip

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值