用Java实现简易记事本
时间: 2023-10-11 08:10:36 浏览: 175
好的,这是一个简单的Java记事本的实现示例:
```java
import java.io.*;
import java.util.Scanner;
public class SimpleNotepad {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Simple Notepad!");
while (true) {
System.out.println("Enter '1' to create a new file, '2' to open an existing file, or '3' to exit:");
int choice = scanner.nextInt();
switch (choice) {
case 1:
createFile();
break;
case 2:
openFile();
break;
case 3:
System.out.println("Exiting Simple Notepad...");
System.exit(0);
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
private static void createFile() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name of the file to create:");
String filename = scanner.nextLine();
try {
File file = new File(filename);
if (file.createNewFile()) {
System.out.println("File created: " + file.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
FileWriter writer = new FileWriter(file);
System.out.println("Enter text to write to the file:");
String text = scanner.nextLine();
writer.write(text);
writer.close();
System.out.println("Text written to file.");
} catch (IOException e) {
System.out.println("Error creating file: " + e.getMessage());
}
}
private static void openFile() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name of the file to open:");
String filename = scanner.nextLine();
try {
File file = new File(filename);
if (file.exists()) {
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
System.out.println("File contents:");
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} else {
System.out.println("File does not exist.");
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
```
这个简单的记事本程序提供了三个选项:创建新文件、打开现有文件或退出程序。如果选择创建新文件,程序会要求用户输入文件名和要写入文件的文本。如果选择打开现有文件,程序会要求用户输入文件名并显示文件内容。
阅读全文