package day11;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* 完成记事本功能
* 要求:
* 程序启动后,要求用户输入一个文件名,然后创建该文件,
* 之后提示用户开始输入内容,并将用户输入的每一行内容都
* 按行写入到该文件。
* 当用户输入"exit"时,退出程序。
* @author Administrator
*
*/
class NotePad{
String noteName;//文件名称
/*
* 构造方法:以文件名为参数,并调用newNotePad()方法创建文件
*/
public NotePad(String noteName) throws IOException {
super();
this.noteName = noteName;
newNotePad(this.noteName);
}
public String getNoteName() {
return noteName;
}
public void setNoteName(String noteName) {
this.noteName = noteName;
}
@Override
public String toString() {
return "note [noteName=" + noteName + "]";
}
/*
* 创建以noteName为名称的文件,并判断是否已存在
*/
public void newNotePad(String noteName) throws IOException {
File file = new File(noteName);
if(!file.exists()) {
file.createNewFile();
System.out.println("文件"+noteName+"创建成功");
}else {
System.out.println("文件"+noteName+"已存在");
}
}
/*
* 文件写出方法
*/
public void notePrint() throws IOException {
// PrintWriter pwPrintWriter = new PrintWriter(noteName, "UTF-8");
FileOutputStream fos = new FileOutputStream(noteName);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
//自动行刷新
PrintWriter pwPrintWriter = new PrintWriter(osw, true);
String string = null;
Scanner scanner = new Scanner(System.in);
while(!("exit".equals( string = scanner.nextLine() ) )) {
pwPrintWriter.println(string);
/*
* 若PrintWriter具有自动行刷新功能
* 那么每当调用println方法后会自动
* flush()
*/
}
System.out.println("写出结束!");
pwPrintWriter.close();
}
}
public class Note {
public static void main(String[] args) throws IOException {
System.out.println("请输入文件名:");
Scanner scanner = new Scanner(System.in);
NotePad notePad = new NotePad(scanner.nextLine());
System.out.println("请开始输入内容,以exit结束:");
notePad.notePrint();
}
}