【Java代码】:实现文本内容修改

代码A

【代码说明】

解释:

基于面向对象的思想,代码的可扩展性强;

利于嫁接其他代码,实现更为强大的功能;

思路:

将"旧的字符串"和"新的字符串"记录到一个文本文件中;

  • 新旧字符串记录在一行,以特殊字符分割开来;
  • 用行读的方式读取每行,将新旧字符信息保留;

以行读的方式读取要修改文本文件,替换后保存起来;

  • 每行都与所有旧字符串进行比对,并存新文件;
  • 完成后删除旧文件后修改新文件名为旧文件名;

诉求:

给个关注,随时都能更新,希望给出意见和建议;

【实现代码】

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 文本文件内容替换工具
 *
 * @author SUNxRUN
 */
public class TextReplacement {
    // 要操作的文件
    public File sourceFile = new File("E:\\1.txt");
    // 替换文本文件
    public File textFile = new File("E:\\textReplacement.txt");

    /**
     * 新文本和老文本的获取方法
     * 用"新文本"来代替"老文本"
     * 通过在文本文件中输入的方式获取
     * 可以定义任意对的替换内容
     *
     * @param textFile 存替换文本的文件
     * @return 返回的是"新老文本"键值对
     */
    public Map<String, String> replacementText(File textFile) {
        // 文件输入相关流的创建
        FileInputStream fis;
        InputStreamReader isr;
        BufferedReader br = null;
        // 容器,用来存放替换文本信息
        Map<String, String> str = new HashMap<>();
        try {
            fis = new FileInputStream(textFile);
            isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            br = new BufferedReader(isr);

            // 从文本文件中获取到替换文本的相关信息
            String line;
            while ((line = br.readLine()) != null) {
                // 判定读取到的文本行是否是要替换的文本
                if (line.contains("---") && line.trim().length() > 4) {
                    // 将老文本和文本以键值对的形式存入Map容器中
                    // 新老文本的分割符号是:"---"
                    str.put(line.split("---")[0], line.split("---")[1]);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    /**
     * 单个文件内容的替换
     * 读取要操作的文本文件
     * 实现文本替换功能
     * 并创建新文件替代
     * 修改成原文件名即可
     *
     * @param sourceFile 要操作的文本文件
     */
    public void operationDocument(File sourceFile) {
        // 用于临时周转的文本文件
        File temporaryFile = new File("E:\\temporaryFile");
        // 文件输入相关流的创建
        FileInputStream fis;
        InputStreamReader isr;
        BufferedReader br = null;
        // 文件输出相关流的创建
        FileOutputStream fos;
        OutputStreamWriter osw;
        BufferedWriter bw;
        PrintWriter pw = null;

        try {
            fis = new FileInputStream(sourceFile);
            isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            br = new BufferedReader(isr);

            fos = new FileOutputStream(temporaryFile, true);
            osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            bw = new BufferedWriter(osw);
            pw = new PrintWriter(bw, true);

            // 从文本文件中获取到替换文本的相关信息
            String line;
            while ((line = br.readLine()) != null) {
                Map<String, String> str = replacementText(textFile);
                Set<String> oldStrs = str.keySet();
                // 每一行都与所有替换文本比对
                for (String oldStr : oldStrs) {
                    if (line.contains(oldStr)) {
                        line = line.replace(oldStr, str.get(oldStr));
                    }
                }
                pw.println(line);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sourceFile.delete();
        temporaryFile.renameTo(sourceFile);
    }

    public static void main(String[] args) {
        TextReplacement textReplacement = new TextReplacement();
        textReplacement.operationDocument(textReplacement.sourceFile);
    }
}

代码B

【代码说明】

解释:

基于代码A进行了优化和完善,可扩展性更强;

每个方法都可以独立存在,不存在嵌套和黏连;

做了方法的重载,适用的情况更加多,更明了;

思路:

将"旧的字符串"和"新的字符串"记录到一个文本文件中;

  • 新旧字符串记录在一行,以特殊字符分割开来;
  • 用行读的方式读取每行,将新旧字符信息保留;

也可以通过其他的方式来设置"新旧字符串"键值对内容;

  • 最终是将其存放到一个"Map"中进行返回和使用的;

以行读的方式读取要修改文本文件,替换后保存起来;

  • 每行都与所有旧字符串进行比对,并存新文件;
  • 完成后删除旧文件后修改新文件名为旧文件名;

【实现代码】

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 单个文本文件的多项内容实现修改
 *
 * @author SUNxRUN
 */
public class TextReplacement {
    /**
     * 要修改内容的文本文件
     * <p>
     * 默认设置,用于测试
     */
    public File sourceFile = new File("E:\\1.txt");
    /**
     * 用来存"老-新"字符键值对的文件
     * <p>
     * 用于快速设置的目的
     */
    private File textFile = new File("E:\\textReplacement.txt");

    /**
     * 替换内容相关信息的获取操作
     * 分隔符是固定的"---"的情况
     * <p>
     * 通过在文本文件中输入
     * "老-新"字符对的方式
     * 完成要修改内容的编辑
     *
     * @param textFile 存"老-新"字符键值对的文件
     * @return 一个容器, 包含"老-新"字符键值对内容
     */
    public Map<String, String> replacementText(File textFile) {
        /* 文件输入流的创建*/
        FileInputStream fis;
        InputStreamReader isr;
        BufferedReader br = null;
        // 容器,用来存放"老-新"字符键值对
        Map<String, String> str = new HashMap<>();
        try {
            /* 文件输入相关流的使用*/
            fis = new FileInputStream(textFile);
            isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            br = new BufferedReader(isr);
            // 用来存放读取到的每行的文本信息
            String line;
            /* 按照行读的方式,读完终止*/
            while ((line = br.readLine()) != null) {
                // 判定读取到的文本行是否是"老-新"键值对信息
                if (line.contains("---") && line.trim().length() > 4) {
                    // 将老文本和文本以键值对的形式存入Map容器中
                    // 新老文本的分割符号是:"---"
                    str.put(line.split("---")[0].trim(), line.split("---")[1].trim());
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭输入流
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    /**
     * 替换内容相关信息的获取操作
     * 分隔符是自己来设定的情况
     * <p>
     * 通过在文本文件中输入
     * "老-新"字符对的方式
     * 完成要修改内容的编辑
     *
     * @param textFile  用来存"老-新"字符键值对的文件
     * @param separator 用来设定"老-新"字符键值对的分隔符
     * @return 一个容器, 包含"老-新"字符键值对内容
     */
    public Map<String, String> replacementText(File textFile, String separator) {
        // 在外声明,以便于关闭输入流
        BufferedReader br = null;
        // 容器,用来存放"老-新"字符键值对
        Map<String, String> str = new HashMap<>();
        try {
            /* 文件输入相关流的使用*/
            FileInputStream fis = new FileInputStream(textFile);
            InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            br = new BufferedReader(isr);
            // 用来存放读取到的每行的文本信息
            String line;
            /* 按照行读的方式,读完终止*/
            while ((line = br.readLine()) != null) {
                // 判定读取到的文本行是否是"老-新"键值对信息
                if (line.contains(separator) && line.trim().length() > 4) {
                    // 将老文本和文本以键值对的形式存入Map容器中
                    // 新老文本的分割符号是:"---"
                    str.put(line.split(separator)[0].trim(), line.split(separator)[1].trim());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭输入流
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    /**
     * 文件内容的修改具体操作
     * 通过文件复制的方式来完成
     * <p>
     * 原文件一行一行的比对后
     * 修改内容并传入周转文件
     * 删原文件修改周转文件名
     *
     * @param sourceFile 要进行修改的文本文件
     * @param strs       要修改内容的"老-新"字符键值对
     */
    public void operationDocument(File sourceFile, Map<String, String> strs) {
        // 用于临时周转的文本文件
        File temporaryFile = new File("E:\\temporaryFile");
        /* 文件输入相关流的创建*/
        FileInputStream fis;
        InputStreamReader isr;
        BufferedReader br = null;
        /* 文件输出相关流的创建*/
        FileOutputStream fos;
        OutputStreamWriter osw;
        BufferedWriter bw;
        PrintWriter pw = null;
        try {
            /* 文件输入流的使用*/
            fis = new FileInputStream(sourceFile);
            isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            br = new BufferedReader(isr);
            /* 文件输出流的使用*/
            fos = new FileOutputStream(temporaryFile);
            osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            bw = new BufferedWriter(osw);
            pw = new PrintWriter(bw, true);
            // 每行的内容
            String line;
            /* 读完为主*/
            while ((line = br.readLine()) != null) {
                // "老"字符所有的值的获取
                Set<String> oldStrs = strs.keySet();
                /* 每一行都与所有的"老"字符值进行比对*/
                for (String oldStr : oldStrs) {
                    /* 如果包含,就换掉*/
                    if (line.contains(oldStr)) {
                        line = line.replace(oldStr, strs.get(oldStr));
                    }
                }
                // 到此就说明这一行都ok了,进行写入操作
                pw.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                /* 关闭输入和输出流*/
                br.close();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        /* 完成后,删除原文件,周转文件改名为原文件名,表面看就是完成了修改内容的操作*/
        sourceFile.delete();
        temporaryFile.renameTo(sourceFile);
    }

    /**
     * 文本文件复制的具体操作
     *
     * @param sourceFile 要复制的源文件
     * @param targetFile 复制后目标文件
     */
    public void operationDocument(File sourceFile, File targetFile) {
        // 放在外面,便于关闭输入流
        BufferedReader br = null;
        // 放在外面,便于关闭输出流
        PrintWriter pw = null;
        try {
            /* 文件输入流的使用*/
            FileInputStream fis = new FileInputStream(sourceFile);
            InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            br = new BufferedReader(isr);
            /* 文件输出流的使用*/
            FileOutputStream fos = new FileOutputStream(targetFile);
            OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            pw = new PrintWriter(bw, true);
            // 每行的内容
            String line;
            /* 读完为主*/
            while ((line = br.readLine()) != null) {
                pw.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                /* 关闭输入和输出流*/
                br.close();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 文本文件另存为的具体操作
     * 修改完毕后保存为新的文件
     *
     * @param sourceFile 要复制的源文件
     * @param targetFile 复制后目标文件
     * @param strs       要修改内容的"老-新"字符键值对
     */
    public void operationDocument(File sourceFile, File targetFile, Map<String, String> strs) {
        // 放在外面,便于关闭输入流
        BufferedReader br = null;
        // 放在外面,便于关闭输出流
        PrintWriter pw = null;
        try {
            /* 文件输入流的使用*/
            FileInputStream fis = new FileInputStream(sourceFile);
            InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            br = new BufferedReader(isr);
            /* 文件输出流的使用*/
            FileOutputStream fos = new FileOutputStream(targetFile);
            OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            pw = new PrintWriter(bw, true);
            // 每行的内容
            String line;
            /* 读完为主*/
            while ((line = br.readLine()) != null) {
                /* 如果设置了替换内容,则开始替换工作,否则跳过*/
                if (strs != null && strs.size() > 0) {
                    // "老"字符所有的值的获取
                    Set<String> oldStrs = strs.keySet();
                    /* 每一行都与所有的"老"字符值进行比对*/
                    for (String oldStr : oldStrs) {
                        /* 如果包含,就换掉*/
                        if (line.contains(oldStr)) {
                            line = line.replace(oldStr, strs.get(oldStr));
                        }
                    }
                }
                // 到此就说明这一行都ok了,进行写入操作
                pw.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                /* 关闭输入和输出流*/
                br.close();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TextReplacement tr = new TextReplacement();
        tr.operationDocument(tr.sourceFile, tr.replacementText(tr.textFile));
    }

}
  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java是一种广泛使用的面向对象的编程语言,由Sun Microsystems公司于1995年5月正式发布。它的设计目标是“一次编写,到处运行(Write Once, Run Anywhere)”,这意味着开发者可以使用Java编写应用程序,并在支持Java的任何平台上无需重新编译即可运行,这得益于其独特的跨平台性,通过Java虚拟机(JVM)实现不同操作系统上的兼容。 Java的特点包括: 面向对象:Java全面支持面向对象的特性,如封装、继承和多态,使得代码更易于维护和扩展。 安全:Java提供了丰富的安全特性,如禁止指针运算、自动内存管理和异常处理机制,以减少程序错误和恶意攻击的可能性。 可移植性:Java字节码可以在所有安装了JVM的设备上执行,从服务器到嵌入式系统,再到移动设备和桌面应用。 健壮性与高性能:Java通过垃圾回收机制确保内存的有效管理,同时也能通过JIT编译器优化来提升运行时性能。 标准库丰富:Java拥有庞大的类库,如Java SE(Java Standard Edition)包含基础API,用于开发通用应用程序;Java EE(Java Enterprise Edition)提供企业级服务,如Web服务、EJB等;而Java ME(Java Micro Edition)则针对小型设备和嵌入式系统。 社区活跃:Java有着全球范围内庞大的开发者社区和开源项目,持续推动技术进步和创新。 多线程支持:Java内建对多线程编程的支持,使并发编程变得更加简单直接。 动态性:Java可以通过反射、注解等机制实现在运行时动态加载类和修改行为,增加了程序的灵活性。 综上所述,Java凭借其强大的特性和广泛的适用范围,在企业级应用、互联网服务、移动开发等领域均扮演着举足轻重的角色,是现代软件开发不可或缺的重要工具之一。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

SUNxRUN

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

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

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

打赏作者

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

抵扣说明:

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

余额充值