用java编写一个记事本
时间: 2024-12-23 08:18:10 浏览: 10
在Java中编写一个简单的文本编辑器(记事本),我们可以创建一个基于控制台的应用程序。这里是一个基础的例子,它允许用户打开、读取和保存文本文件:
```java
import java.io.*;
import java.util.Scanner;
class SimpleNotebook {
private String filePath;
public void openFile(String fileName) {
try {
filePath = "notes/" + fileName;
if (new File(filePath).exists()) {
Scanner scanner = new Scanner(new FileReader(filePath));
System.out.println("Content of the file:");
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} else {
System.out.println("File not found.");
}
} catch (FileNotFoundException e) {
System.out.println("Error opening file.");
e.printStackTrace();
}
}
public void saveFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
writer.write("Enter your text to save:");
writer.newLine();
writer.write(Console.input());
writer.close();
System.out.println("Text saved successfully.");
} catch (IOException e) {
System.out.println("Error saving file.");
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
SimpleNotebook notebook = new SimpleNotebook();
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Simple Text Editor!");
while (true) {
System.out.println("\n1. Open an existing file");
System.out.println("2. Save a new file");
System.out.println("3. Exit");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.print("Enter file name: ");
String fileName = input.next();
notebook.openFile(fileName);
break;
case 2:
notebook.saveFile();
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Invalid option, please try again.");
}
}
}
}
```
在这个例子中,`SimpleNotebook`类包含两个方法:`openFile`用于显示并读取文件内容,`saveFile`用于接收用户的输入并将其保存到指定文件。主函数提供了一个简单的菜单,让用户选择操作。
阅读全文