模拟记事本程序:(注:请用字符流完成如下程序)
创建记事本(Notepad)类,具有如下方法:
public void newFile() {// 新建文件
// StringBuffer类的对象,作为文本临时缓冲区;
// 从控制台输入若干行字符,暂存到缓冲区中;
// 当输入"end"时,表示输入结束
// 询问用户是否保存记事本内容到文件
// 若选择"是",提示用户输入文件全路径及文件名,将缓冲区中的字符存入该文件
}
public void openFile() {// 打开文件
// 提示用户输入要打开的文件全路径及文件名
// 打开用户指定的文件,并将文件原文显示在屏幕上
}
}
创建测试类,输出系统菜单供选择,并根据用户选择调用Notepad类的相应方法完成指定功能。
public class Notepad {
Scanner scan=new Scanner(System.in);
public void newFile() {
// 创建一个StringBuffer类的对象,作为文本临时缓冲区;
StringBuffer sb=new StringBuffer();
String str=scan.nextLine();
// 从控制台输入若干行字符,暂存到缓冲区中,当输入"end"时,输入结束;
while(!str.equals("end")) {
sb.append(str+"\r\n");
str=scan.nextLine();
}
// 询问用户是否保存记事本内容到文件
System.out.println("文件是否需要保存?(Y/N)");
String save=scan.nextLine();
// 若选择"是",提示用户输入文件全路径及文件名,将缓冲区中的字符存入该文件
if(save.equals("Y")||save.equals("y")) {
System.out.println("请输入文件全路径及文件名。格式:绝对路径\\主文件名");
String fileName=scan.nextLine();
FileWriter fw=null;
try {
fw=new FileWriter(fileName+".txt");
str=sb.toString();
fw.write(str);
}catch(IOException e) {
e.printStackTrace();
}finally{
try {
if(fw!=null) fw.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
public void openFile() {
// 提示用户输入要打开的文件全路径及文件名
System.out.println("请输入要打开的文件全路径及文件名。格式:绝对路径\\主文件名");
String fileName=scan.nextLine();
// 打开用户指定的文件,并将文件原文显示在屏幕上
FileReader fr=null;
try {
fr=new FileReader(fileName+".txt");
int len=0;
while((len=fr.read())!=-1) {
char ch=(char)len;
System.out.print(ch);
}
}catch(IOException e) {
e.printStackTrace();
}finally{
try {
if(fr!=null) fr.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
Notepad np=new Notepad();
while(true) {
System.out.println("~~~1. 新建文件 2. 打开文件 0. 退出系统~~~");
System.out.println("请选择你要进行的操作:");
int choice=scan.nextInt();
switch(choice) {
case 0:
System.exit(0);break;
case 1:
np.newFile();
break;
case 2:
np.openFile();
break;
default:
System.out.println("输入的菜单号错误。");
}
}
}
}