前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >文本替换demo

文本替换demo

作者头像
JQ实验室
发布2022-02-14 20:56:42
1K0
发布2022-02-14 20:56:42
举报
文章被收录于专栏:实用技术实用技术
代码语言:javascript
复制
package com.na.ip;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws UnknownHostException, IOException {

        String local = "localhost";
        String server = "baseserver";
        String ip = getLocalIp();
        String baseserver = "";
        String folder = getJarDir();
        System.out.println("当前路径为:" + folder);
        System.out.println("本机ip为:" + ip);
        System.out.println("是否正确(Y/N)?");
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        if ("Y".equalsIgnoreCase(str)) {
        } else {
            System.out.println("输入本机IP:");
            sc = new Scanner(System.in);
            str = sc.nextLine();
            ip = str;
        }
        System.out.println("输入基础服务机器IP(多个需要,隔开):");
        sc = new Scanner(System.in);
        str = sc.nextLine();
        baseserver = str;
        if (args != null && args.length > 0 && args[0].equalsIgnoreCase("vip")) {
            if (args.length > 2 && args[1].equals("vvip")) {
                System.out.println("输入源文件夹路径:");
                sc = new Scanner(System.in);
                str = sc.nextLine();
                folder = str;
            }

            System.out.println("输入本机IP需要替换的字符串:");
            sc = new Scanner(System.in);
            str = sc.nextLine();
            local = str;
            System.out.println("输入基础服务机器IP需要替换的字符串:");
            sc = new Scanner(System.in);
            str = sc.nextLine();
            server = str;
        }
        System.out.println("本机ip为:" + ip + ",将替换字符串:" + local + ";基础服务ip为:" + baseserver + ",将替换字符串:" + server);
        System.out.println("输入目标文件夹路径:");
        sc = new Scanner(System.in);
        str = sc.nextLine();
        String dest = str;

        File dir = new File(folder);
        for (File file : dir.listFiles()) {
            if (!file.isDirectory()) {
                continue;
            }
            String folderName = file.getName();
            File serverFolder = new File(dest + File.separator + folderName);
            if (!serverFolder.exists()) {
                serverFolder.mkdirs();
            }
            for (File configFile : file.listFiles()) {
                if (!configFile.isDirectory()) {
                    continue;
                }
                String configFolderName = configFile.getName();
                File configFolder = new File(serverFolder.getAbsoluteFile() + File.separator + configFolderName);
                if (!configFolder.exists()) {
                    configFolder.mkdirs();
                }
                for (File config : configFile.listFiles()) {
                    if (config.isDirectory()) {
                        continue;
                    }
                    String name = config.getName();
                    File configTxt = new File(configFolder.getAbsoluteFile() + File.separator + name);
                    System.out.println("开始替换" + config.getAbsolutePath() + "文件内容:");
                    if(name.contains("ignite") && baseserver.split(",|,").length > 1 
                            && server.split(",|,").length == baseserver.split(",|,").length) {
                        replacTextContent(config.getAbsolutePath(),baseserver.split(",|,"),
                                server.split(",|,"), configTxt.getAbsolutePath());
                        replacTextContent(configTxt.getAbsolutePath(),new String[] { local },
                                new String[] { ip }, configTxt.getAbsolutePath());
                        
                    }else {
                        replacTextContent(config.getAbsolutePath(), new String[] { local, server },
                                new String[] { ip, baseserver }, configTxt.getAbsolutePath());
                    }
                }
            }

        }

    }

    // 获取jar目录
    public static String getJarDir() {
        File file = getFile();
        if (file == null)
            return null;
        return getFile().getParent();
    }

    public static File getFile() {
        String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        try {
            path = java.net.URLDecoder.decode(path, "UTF-8");// 转换处理中文及空格
        } catch (java.io.UnsupportedEncodingException e) {
            return null;
        }
        return new File(path);
    }

    /**
     * 替换文本文件中的字符串
     * 
     * @param path
     * @throws IOException
     */
    public static void replacTextContent(String path, String[] srcStr, String[] replaceStr, String dest){
        try {
            // 读
            File file = new File(path);
            //FileReader in = new FileReader(file);
            BufferedReader bufIn = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            // 内存流, 作为临时流
            //CharArrayWriter tempStream = new CharArrayWriter();
            OutputStreamWriter tempStream = new OutputStreamWriter(new FileOutputStream(new File(dest)),"UTF-8");
            // 替换
            String line = null;
            while ((line = bufIn.readLine()) != null) {
                // 替换每行中, 符合条件的字符串
                for (int i = 0; i < srcStr.length; i++) {
                    line = line.replaceAll(srcStr[i], replaceStr[i]);
                }
                // 将该行写入内存
                tempStream.write(line);
                // 添加换行符
                tempStream.append(System.getProperty("line.separator"));
            }
            // 关闭 输入流
            bufIn.close();
            // 将内存中的流 写入 文件
            //FileWriter out = new FileWriter(new File(dest));
            //tempStream.writeTo(out);
            //out.close();
            tempStream.close();
            System.out.println("替换结束,生成文件路径:" + dest);
        } catch (Throwable e) {
            System.err.println("替换"+path+"文件失败!");
        }
        

    }

    public static String getLocalIp() throws UnknownHostException {
        InetAddress address = InetAddress.getLocalHost();
//        System.out.println(address);// 获取计算机名称和ip地址
        String hostAddress = address.getHostAddress();
//        System.out.println(hostAddress);// 获取ip地址
//        String hostName = address.getHostName();
//        System.out.println(hostName);// 获取计算机名称
        return hostAddress;
    }
}

编译运行:

javac -encoding utf-9 Main.java

java Main

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档