(以前的好不小心注销了怎办)

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


package Action;
 
import java.io.*;
 
/**
 * @author laoshifu
 * @date 2022年1月3日11:17:09
 */
public class demos {
    public static void main(String[] args) throws IOException {
        FileWriter fw= null;
        FileReader fr=null;
        try {
            fw = new FileWriter(new File("E:/test/data.txt"));
            String str="学号:89757 \t 姓名:林俊杰\n";
            str+="兴趣爱好:唱歌,写词曲\n";
            str+="座右铭:粉丝万万岁";
            fw.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            fw.flush();//刷新,写完必须刷一下
            fw.close();
        }
        fr = new FileReader(new File("E:/test/data.txt"));
        while (true) {
            int read = fr.read();
            if (read == -1) {
                break;
            }
            System.out.print((char) read);
        }
        fr.close();
    }
}

示例代码如下:

public class Demo {

    public static void main(String[] args) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"));
        writer.write("学号:1,姓名:张三\n");
        writer.write("兴趣爱好:篮球\n");
        writer.write("座右铭:day day up");
        writer.flush();
        writer.close();
        BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
}

执行结果如下:

img

如有帮助,请采纳。