search
HomeJavajavaTutorialHow does Java use IO streams to implement simple notepad functions?

Requirements: Write a program that simulates a diary. By entering commands on the console, you can create new files locally, open the diary, and modify the diary.

Command 1 represents "New Diary", which can obtain the diary content input by the user from the console.

Command 2 represents "Open Diary", which reads the contents of the TXT file with the specified path and Output to the console

Command 3 represents "modify diary", modify the original content in the journal

Command 4 represents save

Command 5 represents exit

import java.io.*;
import java.util.Scanner;
public class IO_日记本 {
    /**
     * 模拟日记本程序
     */
    private static String filePath;
    private static String message = "";
 
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("---------日记本---------");
            System.out.println("1.写日记");
            System.out.println("2.查看日记");
            System.out.println("3.修改日记");
            System.out.println("4.保存");
            System.out.println("5.退出");
            System.out.println("注意:每次输入内容后记得保存!");
            System.out.print("请输入操作指令:");
            int command = sc.nextInt();
            switch (command) {
                case 1:
                    // 1:新建文件(写日记)
                    createFile();
                    break;
                case 2:
                    // 2:打开文件(查看日记)
                    openFile();
                    break;
                case 3:
                    // 3:修改文件
                    editFile();
                    break;
                case 4:
                    // 4:保存
                    saveFile();
                    break;
                case 5:
                    // 5:退出
                    System.out.println("谢谢使用本系统,欢迎下次再来!");
                    System.exit(0);
                    break;
                default:
                    System.out.println("您输入的指令错误!");
                    break;
            }
        }
    }
 
    //写一个方法写入文件内容
    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();//将输入内容缓存
    }
 
    //写一个方法保存文件
    private static void saveFile() throws Exception {
        FileWriter out = new FileWriter("文件路径", true);
        out.write(message + "\r\n");//将输入内容写入
        message = "";
        out.close();
    }
 
    //写一个方法打开文件
    public static void openFile() throws Exception {
        Reader r = new FileReader("文件路径");
        BufferedReader br = new BufferedReader(r);
//        char[] c = new char[1024];//定义一个桶装每次读取多少个数据
//        int len;
//        while ((len = br.read(c)) != -1) {//读取所有内容,如果读完所有内容则停止
//            String str = new String(c, 0, len);//每次读取0到len的所有内容
//            System.out.print(str);//因为读取时会自动换行所以这里我们不需要换行
//        }
        String line;
        while ((line = br.readLine()) != null) {//一次读取一行
            System.out.println(line);//因为读取一行时程序不会自己换行,所以这里我们需要给它换行
        }
        //System.out.println();//读完换行
    }
 
    //写一个方法修改文件
    /**
     * 替换
     * @throws IOException
     */
    public static void editFile() throws IOException{
        Scanner sc = new Scanner(System.in);
        //原有的内容
        System.out.println("原文件内容:");
        String str1 =sc.next();;
        //要替换的内容
        System.out.println("修改成:");
        String str2 =sc.next();
        // 读取
        File file = new File("文件路径");
        FileReader in = new FileReader(file);
        BufferedReader buf = new BufferedReader(in);//缓冲流
        // 内存流, 作为临时流
        CharArrayWriter tempStream = new CharArrayWriter();
        // 替换
        String line = null;
        while ( (line = buf.readLine()) != null) {
            // 替换每行中, 符合条件的字符串
            line = line.replaceAll(str1, str2);//正则表达式
            // 将该行写入内存
            tempStream.write(line+"\r\n");
        }
        // 关闭输入流
        buf.close();
        // 将内存中的流写入文件
        FileWriter fw = new FileWriter(file);
        tempStream.writeTo(fw);
        fw.close();
    }
}

The above is the detailed content of How does Java use IO streams to implement simple notepad functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor