import java.io.*;
import java.util.Scanner;
public class Notepad {
private static StringBuilder textContent = new StringBuilder(); // 用于存储当前文本内容
private static String filePath = ""; // 用于存储当前打开或保存的文件路径
private static Scanner scanner = new Scanner(System.in); // 添加的Scanner变量
public static void main(String[] args) {
boolean isRunning = true;
while (isRunning) {
System.out.println("请输入指令:");
System.out.println("1 - 新建文本");
System.out.println("2 - 打开文本");
System.out.println("3 - 修改文本");
System.out.println("4 - 保存");
System.out.println("5 - 退出");
int choice = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
switch (choice) {
case 1:
createText(scanner);
break;
case 2:
openText(scanner);
break;
case 3:
editText(scanner);
break;
case 4:
saveText(scanner);
break;
case 5:
isRunning = false;
break;
default:
System.out.println("无效的指令,请重新输入。");
break;
}
}
}
private static void createText(Scanner scanner) {
System.out.println("请输入新的文本内容:");
textContent.setLength(0); // 清空文本内容
textContent.append(scanner.nextLine()); // 读取用户输入的内容
System.out.println("请输入要保存的文件路径:");
filePath = scanner.nextLine(); // 读取用户输入的文件路径
System.out.println("新建文本内容已保存。");
}
private static void openText(Scanner scanner) {
System.out.println("请输入文本文件路径:");
filePath = scanner.nextLine();
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
textContent.append(line).append("\n");
}
reader.close();
System.out.println("文本内容已打开:\n" + textContent);
} catch (IOException e) {
System.out.println("无法打开文本文件:" + e.getMessage());
}
}
private static void editText(Scanner scanner) {
if (textContent.length() == 0) {
System.out.println("文本内容为空,请先新建或打开文本。");
} else {
System.out.println("请输入要替换的内容:");
String target = scanner.nextLine();
System.out.println("请输入替换后的内容:");
String replacement = scanner.nextLine();
textContent = new StringBuilder(textContent.toString().replace(target, replacement));
System.out.println("文本内容已修改。");
}
}
private static void saveText(Scanner scanner) {
if (textContent.length() == 0) {
System.out.println("文本内容为空,无法保存。");
} else {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
writer.write(textContent.toString());
writer.close();
System.out.println("文本内容已保存至:" + filePath);
} catch (IOException e) {
System.out.println("无法保存文本文件:" + e.getMessage());
}
}
}
}
本案例要求编写一个模拟日记本的程序,通过在控制台输入指令,实现在本地新建日记本、打开日记本和修改日记本等功能。
(1)用户输入指令1代表“新建日记本”,可以从控制台获取用户输入的日记内容。
(2)指令2代表“打开日记本”,读取指定路径的txt文件的内容并输出到控制台。
(3)指令3代表“修改日记本”,修改日记时,既可以修改新建日记本的内容,也可以修改已打开日记本的内容。
(4)指令4代表“保存”,如果是新建的日记本需要保存,则将日记本保存到用户输入的路径;如果是打开的日记本需要保存,则将原来内容覆盖;
指令5代表“退出”,即退出本系统