1. 程式人生 > 實用技巧 >個人寫的文字替換小程式

個人寫的文字替換小程式

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Database2DatabaseUtil {

    //輸出計數,方便觀察
    private static int count = 0;

    public static void main(String[] args) throws IOException {
        
//只需替換Map即可 replaceAllFile("D:\\ningxinjie\\code\\b2bcode\\util\\file", "D:\\ningxinjie\\code\\b2bcode\\util\\new-File", design2OnlineMap); } //design切online static Map<String, String> design2OnlineMap = new HashMap<>(); //使用示例:design2OnlineMapPattern.put("cms01","cms01(!A)")
static Map<String, String> design2OnlineMapPattern = new HashMap<>(); //online切ck static Map<String, String> doris2CkMap = new HashMap<>(); static Map<String, String> doris2CkMapPattern = new HashMap<>(); //design切ck static Map<String, String> design2DorisMap = new
HashMap<>(); static Map<String, String> design2DorisMapPattern = new HashMap<>(); /** * 替換所有新檔案 * * @param rootPath * @param targetPath * @param map * @return */ public static boolean replaceAllFile(String rootPath, String targetPath, Map<String, String> map) { return replaceAllFile(rootPath, targetPath, map, null); } /** * 替換所有新檔案(包含正則) * * @param rootPath 原位置 * @param targetPath 目標位置 * @param map 替換選項,【如果為null則複製】 * @param mapPattern 正則選項,【如果為null則不使用正則】 * 內部呼叫 replaceTxt * @return */ public static boolean replaceAllFile(String rootPath, String targetPath, Map<String, String> map, Map<String, String> mapPattern) { File file = new File(rootPath); if (file.isFile()) { replaceTxt(rootPath, targetPath, true, map, mapPattern); } else if (file.isDirectory()) { //確保目錄存在 File targetFile = new File(targetPath); if (!targetFile.exists() && !targetFile.isDirectory()) targetFile.mkdir(); String[] list = file.list(); for (String s : list) { replaceAllFile(rootPath + "\\" + s, targetPath + "\\" + s, map, mapPattern); } } else { System.out.println("輸入異常..." + rootPath); return false; } return true; } /** * @param oldfilePath 源文字地址 * @param newfilePath 新文字地址 * @param isOverride 新文字如果存在是否覆蓋 * @param map 要替換的map * @param mapPattern 正則替換(為了處理一些假如cms03 與 cms03A 我們想替換不影響,這時候就需要如cms03(?!A)這樣的正則表示式來規定,如果不需要傳null即可) * @return */ public static boolean replaceTxt(String oldfilePath, String newfilePath, boolean isOverride, Map<String, String> map, Map<String, String> mapPattern) { if (oldfilePath.equals("D:\\ningxinjie\\code\\b2bcode\\util\\abc\\dimension\\FindDimension.java")) { System.out.println(1); } File file = new File(oldfilePath); File newfile = new File(newfilePath); if (!isOverride && newfile.exists()) { System.out.println("原始檔存在"); return false; } //判斷檔案存在並且是檔案 Boolean isFile = file.exists() && file.isFile(); if (isFile) { BufferedReader bufferedReader = null; BufferedWriter bufferedWriter = null; try { //構造一個BufferedReader類來讀取檔案 bufferedReader = new BufferedReader(new FileReader(file)); //構建一個BufferedWriter類來寫檔案 bufferedWriter = new BufferedWriter(new FileWriter(newfilePath)); String linetxt = null; //result用來儲存檔案內容 StringBuilder result = new StringBuilder(); //按使用readLine方法,一次讀一行 while ((linetxt = bufferedReader.readLine()) != null) { String newcontent = linetxt; if (map != null) { Set<Map.Entry<String, String>> entries = map.entrySet(); for (Map.Entry<String, String> entry : entries) { //判斷是否需要使用正則 if (mapPattern != null && mapPattern.containsKey(entry.getKey())) { newcontent = regReplace(newcontent, mapPattern.get(entry.getKey()), entry.getValue()); } else { newcontent = newcontent.replace(entry.getKey(), entry.getValue());//替換 } } } bufferedWriter.write(newcontent + "\n");//\r\n //bufferedWriter.newLine(); } } catch (Exception e) { System.out.println("讀取檔案內容出錯"); e.printStackTrace(); } finally { try { bufferedWriter.close(); bufferedReader.close(); } catch (IOException e1) { e1.printStackTrace(); } } } else { System.out.println("輸入異常!源目錄不是一個檔案!"); return false; } System.out.println("資料輸出完成" + (++count)); return true; } /** * 正則使用 * * @param content 原文字 * @param pattern 正則表示式 * @param newString 正則匹配項替換文字 * @return */ public static String regReplace(String content, String pattern, String newString) { Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(content); String result = m.replaceAll(newString); return result; } /** * 建立空檔案(臨時建立檔案,接收文字使用) * * @param path 路徑 * @param fileNames 名字集合 * @throws IOException */ public static void createNewFile(String path, String[] fileNames) throws IOException { for (String fileName : fileNames) { File file = new File(path + "\\f-" + fileName); file.createNewFile(); } } }
View Code
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Database2DatabaseUtil {

    //輸出計數,方便觀察
    private static int count = 0;

    public static void main(String[] args) throws IOException {
        //只需替換Map即可
        replaceAllFile("D:\\ningxinjie\\code\\b2bcode\\util\\file",
                "D:\\ningxinjie\\code\\b2bcode\\util\\new-File", design2OnlineMap);
    }

    //design切online
    static Map<String, String> design2OnlineMap = new HashMap<>();
    //使用示例:design2OnlineMapPattern.put("cms01","cms01(!A)")
    static Map<String, String> design2OnlineMapPattern = new HashMap<>();

    //online切ck
    static Map<String, String> doris2CkMap = new HashMap<>();
    static Map<String, String> doris2CkMapPattern = new HashMap<>();

    //design切ck
    static Map<String, String> design2DorisMap = new HashMap<>();
    static Map<String, String> design2DorisMapPattern = new HashMap<>();

    /**
     * 替換所有新檔案
     *
     * @param rootPath
     * @param targetPath
     * @param map
     * @return
     */
    public static boolean replaceAllFile(String rootPath, String targetPath, Map<String, String> map) {
        return replaceAllFile(rootPath, targetPath, map, null);
    }

    /**
     * 替換所有新檔案(包含正則)
     *
     * @param rootPath   原位置
     * @param targetPath 目標位置
     * @param map        替換選項,【如果為null則複製】
     * @param mapPattern 正則選項,【如果為null則不使用正則】
     *                   內部呼叫 replaceTxt
     * @return
     */
    public static boolean replaceAllFile(String rootPath, String targetPath, Map<String, String> map, Map<String, String> mapPattern) {
        File file = new File(rootPath);
        if (file.isFile()) {
            replaceTxt(rootPath, targetPath, true, map, mapPattern);
        } else if (file.isDirectory()) {
            //確保目錄存在
            File targetFile = new File(targetPath);
            if (!targetFile.exists() && !targetFile.isDirectory()) targetFile.mkdir();
            String[] list = file.list();
            for (String s : list) {
                replaceAllFile(rootPath + "\\" + s, targetPath + "\\" + s, map, mapPattern);
            }
        } else {
            System.out.println("輸入異常..." + rootPath);
            return false;
        }
        return true;
    }

    /**
     * @param oldfilePath 源文字地址
     * @param newfilePath 新文字地址
     * @param isOverride  新文字如果存在是否覆蓋
     * @param map         要替換的map
     * @param mapPattern  正則替換(為了處理一些假如cms03 與 cms03A 我們想替換不影響,這時候就需要如cms03(?!A)這樣的正則表示式來規定,如果不需要傳null即可)
     * @return
     */
    public static boolean replaceTxt(String oldfilePath, String newfilePath, boolean isOverride, Map<String, String> map, Map<String, String> mapPattern) {
        if (oldfilePath.equals("D:\\ningxinjie\\code\\b2bcode\\util\\abc\\dimension\\FindDimension.java")) {
            System.out.println(1);
        }
        File file = new File(oldfilePath);
        File newfile = new File(newfilePath);

        if (!isOverride && newfile.exists()) {
            System.out.println("原始檔存在");
            return false;
        }
        //判斷檔案存在並且是檔案
        Boolean isFile = file.exists() && file.isFile();
        if (isFile) {
            BufferedReader bufferedReader = null;
            BufferedWriter bufferedWriter = null;
            try {
                //構造一個BufferedReader類來讀取檔案
                bufferedReader = new BufferedReader(new FileReader(file));
                //構建一個BufferedWriter類來寫檔案
                bufferedWriter = new BufferedWriter(new FileWriter(newfilePath));

                String linetxt = null;
                //result用來儲存檔案內容
                StringBuilder result = new StringBuilder();
                //按使用readLine方法,一次讀一行
                while ((linetxt = bufferedReader.readLine()) != null) {
                    String newcontent = linetxt;
                    if (map != null) {
                        Set<Map.Entry<String, String>> entries = map.entrySet();
                        for (Map.Entry<String, String> entry : entries) {
                            //判斷是否需要使用正則
                            if (mapPattern != null && mapPattern.containsKey(entry.getKey())) {
                                newcontent = regReplace(newcontent, mapPattern.get(entry.getKey()), entry.getValue());
                            } else {
                                newcontent = newcontent.replace(entry.getKey(), entry.getValue());//替換
                            }
                        }
                    }
                    bufferedWriter.write(newcontent + "\n");//\r\n
                    //bufferedWriter.newLine();
                }
            } catch (Exception e) {
                System.out.println("讀取檔案內容出錯");
                e.printStackTrace();
            } finally {
                try {
                    bufferedWriter.close();
                    bufferedReader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        } else {
            System.out.println("輸入異常!源目錄不是一個檔案!");
            return false;
        }
        System.out.println("資料輸出完成" + (++count));
        return true;
    }

    /**
     * 正則使用
     *
     * @param content   原文字
     * @param pattern   正則表示式
     * @param newString 正則匹配項替換文字
     * @return
     */
    public static String regReplace(String content, String pattern, String newString) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(content);
        String result = m.replaceAll(newString);
        return result;
    }

    /**
     * 建立空檔案(臨時建立檔案,接收文字使用)
     *
     * @param path      路徑
     * @param fileNames 名字集合
     * @throws IOException
     */
    public static void createNewFile(String path, String[] fileNames) throws IOException {
        for (String fileName : fileNames) {
            File file = new File(path + "\\f-" + fileName);
            file.createNewFile();
        }
    }
}