1. 程式人生 > 實用技巧 >java-實現修改檔案內容(2)

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
}

結果如下圖所示:

結果應該很清晰,當然還有很多類似的,具體看業務需求進行不同的修改即可