java-实现修改文件内容(2)
本篇文章主要是针对与文本特殊字符用java实现对其修改
1 import com.rmis.common.enums.ParamType; 2 import org.apache.commons.io.IOUtils; 3 4 import java.io.*; 5 6 public class FileUpdateUtils { 7 /** 8 * 脚本中参数替换方法 9 * 10 * @param path 文件路径 11 * @param paramKey 参数名 12 * @param paramVal 参数值 13 * @param paramType 参数类型:数值,字符串 14 */ 15 public static void replaceTxt(String path, String paramKey, String paramVal, Enum paramType) { 16 File file = new File(path); 17 BufferedReader bufIn = null; 18 FileReader in = null; 19 // 内存流, 作为临时流 20 CharArrayWriter tempStream = null; 21 FileWriter out = null; 22 try { 23 in = new FileReader(file); 24 bufIn = new BufferedReader(in); 25 // 内存流, 作为临时流 26 tempStream = new CharArrayWriter(); 27 // 替换 28 String line = null; 29 while ((line = bufIn.readLine()) != null) { 30 if (line.contains(paramKey)) { 31 int beginIndex = 0; 32 int endIndex = 0; 33 beginIndex = line.indexOf("="); 34 endIndex = line.lastIndexOf(","); 35 String oldStr = line.substring(beginIndex + 1, endIndex); 36 37 //如果是字符串,手动加上单引号 38 if(paramType.equals(ParamType.STR)){ 39 StringBuffer sb = new StringBuffer(); 40 sb.append("'").append(paramVal).append("'"); 41 paramVal = sb.toString(); 42 } 43 line = line.replace(oldStr, paramVal); 44 } 45 // 将该行写入内存 46 tempStream.write(line); 47 // 添加换行符 48 tempStream.append(System.getProperty("line.separator")); 49 } 50 // 将内存中的流 写入 文件 51 out = new FileWriter(path); 52 tempStream.writeTo(out); 53 } catch (FileNotFoundException e) { 54 e.printStackTrace(); 55 } catch (IOException e) { 56 e.printStackTrace(); 57 } finally { 58 IOUtils.closeQuietly(tempStream); 59 IOUtils.closeQuietly(out); 60 IOUtils.closeQuietly(bufIn); 61 IOUtils.closeQuietly(in); 62 } 63 } 64 65 public static void main(String[] args) { 66 String path = "C:\\Users\\yfhx\\Desktop\\11\\bippar"; 67 String paramKey ="AKQDOP"; 68 String value = "22"; 69 //带引号字符串 '1' 70 replaceTxt(path,paramKey,value,ParamType.STR); 71 //不带引号字符串 1 72 replaceTxt(path,paramKey,value,ParamType.NUM); 73 } 74 }
ParamType类如下:
package com.rmis.common.enums; /** * @ClassName ParamType * @Description TODO * @Author xb * @Date 2020/06/15 19:49 */ public enum ParamType { NUM,STR }
结果如下图所示:
结果应该很清晰,当然还有很多类似的,具体看业务需求进行不同的修改即可
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通