使用java编写一个程序,实现一个简单的文本编辑器,支持插入、删除和替换文本,以及保存和载入文本文件。
时间: 2024-03-12 12:45:24 浏览: 58
Java实现简单的文本编辑器
5星 · 资源好评率100%
好的,我可以为您提供一个简单的Java文本编辑器的代码实现。以下是一个基本的文本编辑器,它支持插入、删除和替换文本,以及保存和载入文本文件。
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class TextEditor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuffer buffer = new StringBuffer();
String fileName = "text.txt";
String line = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading file!");
}
System.out.println("Text loaded:");
System.out.println(buffer.toString());
System.out.println("-------------------");
while (true) {
System.out.println("What do you want to do?");
System.out.println("1. Insert text");
System.out.println("2. Delete text");
System.out.println("3. Replace text");
System.out.println("4. Save text");
System.out.println("5. Quit");
int option = scanner.nextInt();
scanner.nextLine();
switch(option) {
case 1:
System.out.println("Enter text to insert:");
String insertText = scanner.nextLine();
System.out.println("Enter position to insert text:");
int insertPosition = scanner.nextInt();
scanner.nextLine();
buffer.insert(insertPosition, insertText);
System.out.println("Text after insertion:");
System.out.println(buffer.toString());
break;
case 2:
System.out.println("Enter starting position of text to delete:");
int deleteStartPosition = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter ending position of text to delete:");
int deleteEndPosition = scanner.nextInt();
scanner.nextLine();
buffer.delete(deleteStartPosition, deleteEndPosition);
System.out.println("Text after deletion:");
System.out.println(buffer.toString());
break;
case 3:
System.out.println("Enter text to replace:");
String replaceText = scanner.nextLine();
System.out.println("Enter starting position of text to replace:");
int replaceStartPosition = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter ending position of text to replace:");
int replaceEndPosition = scanner.nextInt();
scanner.nextLine();
buffer.replace(replaceStartPosition, replaceEndPosition, replaceText);
System.out.println("Text after replacement:");
System.out.println(buffer.toString());
break;
case 4:
try {
FileWriter writer = new FileWriter(fileName);
writer.write(buffer.toString());
writer.close();
System.out.println("Text saved!");
} catch (IOException e) {
System.out.println("Error writing to file!");
}
break;
case 5:
System.out.println("Goodbye!");
System.exit(0);
break;
default:
System.out.println("Invalid option!");
}
}
}
}
```
该程序通过使用`BufferedReader`读取文本文件,将文本加载到`StringBuffer`中。然后,它使用一个无限循环,接受用户的输入并执行相应的操作(插入、删除、替换、保存和退出)。最后,程序使用`FileWriter`将更改后的文本写回文件中。
阅读全文