需求如下: 1.程序启动后,要求用户输入文件名,然后对该文件进行操作 2.在控制台输入的每一行字符串都按行写入到该文件中 3.当用户单独输入exit时程序退出
package com.tedu.io; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; /** * 简易记事本PW编写练习 * * @author Wildmess * */ public class Note { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); System.out.println("请输入文件名:"); String fileName = sc.nextLine(); FileOutputStream fos = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8"); BufferedWriter bw = new BufferedWriter(osw); //这里如果不写true,流都是默认覆盖操作的,重复运行就不会覆盖了 PrintWriter pw = new PrintWriter(bw,true); while(true) { String line = sc.nextLine(); if(line.equals("exit")) { break; } pw.println(line); } System.out.println("程序结束!"); pw.close(); } }测试结果如下: