Java模拟记事本

来源:Java基础案例教程

1、任务描述
模拟记事本,通过在控制台输入指令,实现在本地新建文件、打开文件和修改文件
功能:
1:新建文件
2:打开文件
3:修改文件
4:保存文件
5:退出
2、运行结果
在这里插入图片描述
备注:只是简单运行了一下,可能存在bug和代码不合理的地方,请多多包含

实现代码
(1)创建记事本类,在类中编写执行程序的main方法

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
 * 创建记事本类,在类中编写执行程序的main方法
 */
public class Notepad {
	private static String filePath; // 保存文件的路径
	private static String message = ""; // 保存文件内容

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("--1:新建文件  2:打开文件 3:修改文件 4:保存 5:退出--");
		while (true) {
			System.out.println("请输入操作指令:");
			int command = sc.nextInt();
			switch (command) {
			case 1:
				createFile(); // 新建文件
				break;
			case 2:
				openFile(); // 打开文件
				break;
			case 3:
				editFile(); // 修改文件
				break;
			case 4:
				saveFile(); // 保存文件
				break;
			case 5:
				exit(); // 退出
				break;
			default:
				System.out.println("您输入的指令错误!");
				break;
			}
		}
	}

(2)在Notepad中编写新建文件的方法

   /**
	 * 新建文件,从控制台获取内容
	 */
	private static void createFile() {
		message = ""; // 新建文件时,暂存文件内容清空
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入内容,停止编写请输入\"stop\":");
		StringBuffer stb = new StringBuffer(); // 用于后期输入内容的拼接
		String inputMessage = ""; // 接收输入的内容
		while (!inputMessage.equals("stop")) { // 输入stop时停止输入
			if (stb.length() > 0) {
				stb.append("\r\n"); // 追加换行符
			}
			stb.append(inputMessage); // 拼接输入的信息
			inputMessage = sc.nextLine(); // 获取输入信息
		}
		message = stb.toString(); // 将输入的内容暂存
	}

(3)在Notepad中编写打开文件的方法

    /**
	 * 打开文件
	 */
	private static void openFile() {
		message = ""; // 新建文件时,暂存文件内容清空
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入打开文件的位置:");
		filePath = sc.next(); // 获取打开文件的路径
		// 控制只能输入txt格式的文件路径
		if (filePath != null && !filePath.endsWith(".txt")) {
			System.out.println("请选择文本文件!");
			return;
		}
		FileReader in = null;
		try {
			in = new FileReader(filePath);
			char[] charArr = new char[1024];
			int len = 0;
			StringBuffer sb = new StringBuffer();
			while ((len = in.read(charArr)) != -1) {
				sb.append(charArr);
			}
			message = sb.toString(); // 将打开文件内容暂存
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			System.out.println("文件内容是:" + "\r\n" + message);
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

(4)在Notepad中编写修改文件的方法


	/**
	 * 修改文件内容,通过字符串替换的形式
	 */
	private static void editFile() {

		if (message == "" && filePath == null) {
			System.out.println("请先新建文件或打开文件");
			return;
		}
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入要修改的内容(以\"修改的目标文字:修改之后的文字\"格式)," + "停止修改请输入\"stop\":");
		String inputMessage = "";
		while (!inputMessage.equals("stop")) {
			inputMessage = sc.nextLine();
			if (inputMessage != null && inputMessage.length() > 0) {
				// 将输入的文字根据 “:”进行拆分
				String[] editMessage = inputMessage.split(":");
				if (editMessage != null && editMessage.length > 0) {
					// 根据输入的信息将文件中内容替换
					message = message.replace(editMessage[0], editMessage[1]);
				}

			}
		}
		System.out.println("修改后的内容:" + "\r\n" + message);
	}


(5)在Notepad中编写保存文件的方法

	/**
	 * 保存,新建文件存在用户输入的路径,打开的文件将原文件覆盖
	 */
	private static void saveFile() {
		Scanner sc = new Scanner(System.in);
		FileWriter out = null;
		// 文件是有打开载入的,将原文件覆盖
		if (filePath != null) {
			try {
				out = new FileWriter(filePath);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else { // 新建的文件
			System.out.println("请输入文件保存的绝对路径:");
			String path = sc.next(); // 获取路径
			filePath = path;
			// 将输入路径中的大写字母替换为小写字母后判断是不是文本格式
			if (!filePath.toLowerCase().endsWith(".txt")) {
				filePath += ".txt";
			}
			try {
				out = new FileWriter(filePath);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 写入暂存的内容
		try {
			out.write(message);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			message = "";
			filePath = null;
		}
	}

(6)在Notepad中编写退出程序的方法

	/**
	 * 退出
	 */
	private static void exit() {
		System.out.println("您已退出系统,谢谢使用!");
		System.exit(0);
	}
}

  • 10
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的 Java 记事本程序,它具有基本的文本编辑和保存功能: ``` import java.awt.*; import java.awt.event.*; import java.io.*; public class Notepad extends Frame implements ActionListener { private TextArea textArea = new TextArea("", 0,0, TextArea.SCROLLBARS_VERTICAL_ONLY); private MenuBar menuBar = new MenuBar(); // first, create a MenuBar item private Menu file = new Menu(); // our File menu // what's going in File? let's see... private MenuItem openFile = new MenuItem(); // an open option private MenuItem saveFile = new MenuItem(); // a save option private MenuItem close = new MenuItem(); // and a close option! public Notepad() { this.setSize(500, 300); // set the initial size of the window this.setTitle("Java Notepad Tutorial"); // set the title of the window setDefaultCloseOperation(EXIT_ON_CLOSE); // set the default close operation (exit when it gets closed) this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); // set a default font for the TextArea // this is why we didn't have to worry about the size of the TextArea! this.getContentPane().setLayout(new BorderLayout()); // the BorderLayout bit makes it fill it automatically this.getContentPane().add(textArea); // add our menu bar into the GUI this.setMenuBar(this.menuBar); this.menuBar.add(this.file); // we'll configure this later // first off, the design of the menuBar itself. Pretty simple, all we need to do // is add a few menus, which will be populated later on this.file.setLabel("File"); // now it's time to work on the content of the File menu, which is simple // because we only need to add three things to it: an Open option, a Save option // and a Close option this.openFile.setLabel("Open"); this.openFile.addActionListener(this); // addActionListener attaches an ActionListener to the MenuItem this.openFile.setShortcut(new MenuShortcut(KeyEvent.VK_O, false)); // set the keyboard shortcut this.file.add(this.openFile); // add it to the "File" menu this.saveFile.setLabel("Save"); this.saveFile.addActionListener(this); this.saveFile.setShortcut(new MenuShortcut(KeyEvent.VK_S, false)); this.file.add(this.saveFile); this.close.setLabel("Close"); // along with our "CTRL+F4" shortcut to close the window, we also have // the default closer, as stated at the beginning of this tutorial. // this means that we actually have TWO shortcuts to close: // 1) the default close operation (example, Alt+F4 on Windows) // 2) CTRL+F4, which we are about to define now: (this one will appear in the label) this.close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false)); this.close.addActionListener(this); this.file.add(this.close); } public void actionPerformed (ActionEvent e) { // if the source of the event was our "close" option if (e.getSource() == this.close) this.dispose(); // dispose all resources and close the application // if the source was the "open" option else if (e.getSource() == this.openFile) { JFileChooser open = new JFileChooser(); // open up a file chooser (a dialog for the user to browse files to open) int option = open.showOpenDialog(this); // get the option that the user selected (approve or cancel) // NOTE: because we are OPENing a file, we call showOpenDialog~ // if the user clicked OK, we have "APPROVE_OPTION" // so we want to open the file if (option == JFileChooser.APPROVE_OPTION) { this.textArea.setText(""); // clear the TextArea before applying the file contents try { // create a scanner to read the file (getSelectedFile().getPath() will get the path to the file) Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath())); while (scan.hasNext()) // while there's still something to read this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea } catch (Exception ex) { // catch any exceptions, and... // ...write to the debug console System.out.println(ex.getMessage()); } } } // and lastly, if the source of the event was the "save" option else if (e.getSource() == this.saveFile) { JFileChooser save = new JFileChooser(); // again, open a file chooser int option = save.showSaveDialog(this); // similar to the open file, only this time we call // showSaveDialog instead of showOpenDialog // if the user clicked OK (and not cancel) if (option == JFileChooser.APPROVE_OPTION) { try { // create a buffered writer to write to a file BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath())); out.write(this.textArea.getText()); // write the contents of the TextArea to the file out.close(); // close the file stream } catch (Exception ex) { // again, catch any exceptions and... // ...write to the debug console System.out.println(ex.getMessage()); } } } } // the main method, for actually creating our notepad and setting it to visible. public static void main(String[] args) { Notepad app = new Notepad(); app.setVisible(true); } } ``` 这个程序使用了 AWT 组件,它提供了一个基本的 GUI 界面,其中包含了一个 TextArea 用于文本编辑,以及菜单栏和菜单项用于打开、保存和关闭文件。在 actionPerformed() 方法中,我们使用 JFileChooser 对话框来打开和保存文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无知的小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值