import java.io.*; import java.util.Scanner;
/** * 简易的文本编译器(3个方法) * openFile() 打开一个文件 * saveFile() 保存一个文件 * findAndReplace() 查找替换 * @author 小仓 */ public class TextEditor { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("欢迎使用简易文本编译器!"); while (true){ System.out.println("/n请选择您的操作:"); System.out.println("1、打开文件"+"\t"+"2、保存文件"+ "\t"+"3、查找替换"+"\t"+"4、退出"); int choise = scanner.nextInt(); scanner.nextLine(); switch (choise){ case 1: openFile(scanner); break; case 2: saveFile(scanner); break; case 3: findAndReplace(scanner); break; case 4: System.out.println("感谢使用简易文本编辑器!"); System.exit(0); break; default: System.out.println("无效的选项,请重新选择!"); break; } } } /** * 读取用户想要查看的文件,并显示文件内容 * @param scaner */ public static void openFile (Scanner scaner){ System.out.println("请输入要打开的文件路径:"); String filePath = scaner.nextLine(); File file = new File(filePath); if (file.exists()){ try ( FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); ){ StringBuilder sb = new StringBuilder(); String line ; //读取文件内容并添加到sb 对象中。并且读完一行换行 while ((line = br.readLine())!=null) { sb.append(line).append("\n"); } System.out.println("文件内容如下:"); System.out.println(sb); } catch (IOException e) { System.out.println("读去文件出错"); } }else { System.out.println("未找到"+filePath+"文件"); } } /** * 用户输入要保存文件路径,并输入内容 * @param scanner */ public static void saveFile(Scanner scanner){ System.out.println("请输入要保存的文件路径:"); String filePath = scanner.nextLine(); System.out.println("请输入文件内容(输入exit结束):"); try (FileWriter fw = new FileWriter(filePath); BufferedWriter bw = new BufferedWriter(fw); ){ String line; while (!"exit".equals(line = scanner.nextLine())){ PrintWriter pw = new PrintWriter(bw); pw.println(line); } System.out.println("文件保存成功"); } catch (IOException e) { System.out.println("保存文件出错"); } } /** * 替换文件内容,首先查找想要修改的目录,然后在文件中查找要修改的内容,输入修改以后的内容 * 然后替换 * @param scanner */ public static void findAndReplace (Scanner scanner){ System.out.println("请输入要查找替换的文件路径:"); String filePath = scanner.nextLine(); try { FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); StringBuilder sb = new StringBuilder(); String line ; while ((line = br.readLine()) !=null){ sb.append(line).append("\n"); } System.out.println("请输入要查找的内容:"); String find = scanner.nextLine(); System.out.println("请输入要替换的内容:"); String and = scanner.nextLine(); String findand = sb.toString().replace(find,and); System.out.println("替换后的内容如下:"); System.out.println(findand); } catch (FileNotFoundException e) { System.out.println("文件不存在"); } catch (IOException e) { System.out.println("读取文件出错"); } } }