版权声明:转载注明来源。Keep Learning and Coding. https://blog.csdn.net/a771581211/article/details/88600671
package day08;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* 完成记事本功能。要求:
* 程序启动后,要求用户输入一个文件名,然后创建该文件
* 之后提示用户开始输入内容并将用户输入的每一行内容
* 都按行写入到该文件。当用户输入"exit"时,退出程序。
* @author kaixu
*
*/
public class NoteBook {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入文件名:");
String filename = scanner.nextLine();
FileOutputStream fos = new FileOutputStream(filename);
OutputStreamWriter osw = new OutputStreamWriter(fos);
//设置自动行刷新
PrintWriter pw = new PrintWriter(osw,true);
System.out.println("请输入需要记录的内容:");
String line = null;
while(true){
line = scanner.nextLine();
if("exit".equals(line)){
System.out.println("退出成功。");
break;
}
/*
* 若PrintWriter具有自动行刷新功能
* 那么每当调用println方法后就会自动flush。
*/
pw.println(line);
// pw.flush();
}
pw.close();
scanner.close();
}
}