编写程序创建文件data.txt

怎么样在程序中实现把如下3行信息写入data.txt:第一行存放你的学号和姓名信息,第二行存放你的兴趣爱好,第三行存放你的个人座右铭。最后,然后再将data.txt文件的所有内容读取并输出在控制台,可有解法

结合一下三段代码,可以实现你要的功能

写入txt文件

// 将集合中的数据写入到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();
        }

    }

读取txt文件

 // 从文本文件中读,将读出的数据存放于集合中
        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();
        }

控制台输出

System.out.println("Tom,12");