用Java修改Window或者Linux下的hosts文件

做了一个用Java语言修改系统host文件的方法,用处不大,权当解闷。


    public synchronized static boolean updateHostName(String hostName, String ip) throws Exception {
        if (StringUtils.isEmpty(hostName) || StringUtils.isEmpty(ip)) {
            throw new BusinessException("HostName or Ip can't be null.");
        }

        if (StringUtils.isEmpty(hostName.trim()) || StringUtils.isEmpty(ip.trim())) {
            throw new BusinessException("HostName or Ip can't be null.");
        }

        String splitter = " ";
        String fileName = null;

        // 判断系统
        if ("linux".equalsIgnoreCase(System.getProperty("os.name"))) {
            fileName = "/etc/hosts";
        } else {
            fileName = "C://WINDOWS//system32//drivers//etc//hosts";
        }

        // 更新设定文件
        List < ? > lines = FileUtils.readLines(new File(fileName));
        List <String> newLines = new ArrayList <String>();
        boolean findFlag = false;
        boolean updateFlag = false;
        for (Object line : lines) {
            String strLine = (String) line;
            if (StringUtils.isNotEmpty(strLine) && !strLine.startsWith("#")) {
                strLine = strLine.replaceAll("/t", splitter);
                int index = strLine.toLowerCase().indexOf(hostName.toLowerCase());
                if (index != -1) {
                    String[] array = strLine.trim().split(splitter);
                    for (String name : array) {
                        if (hostName.equalsIgnoreCase(name)) {
                            findFlag = true;
                            if (array[0].equals(ip)) {
                                // 如果IP相同,则不更新
                                newLines.add(strLine);
                                break;
                            }
                            // 更新成设定好的IP地址
                            StringBuilder sb = new StringBuilder();
                            sb.append(ip);
                            for (int i = 1; i < array.length; i++) {
                                sb.append(splitter).append(array[i]);
                            }
                            newLines.add(sb.toString());
                            updateFlag = true;
                            break;
                        }
                    }

                    if (findFlag) {
                        break;
                    }
                }
            }
            newLines.add(strLine);
        }
        // 如果没有Host名,则追加
        if (!findFlag) {
            newLines.add(new StringBuilder(ip).append(splitter).append(hostName).toString());
        }

        if (updateFlag || !findFlag) {
            // 写设定文件
            FileUtils.writeLines(new File(fileName), newLines);

            // 确认设定结果
            String formatIp = formatIpv6IP(ip);
            for (int i = 0; i < 20; i++) {
                try {
                    boolean breakFlg = false;
                    InetAddress[] addressArr = InetAddress.getAllByName(hostName);

                    for (InetAddress address : addressArr) {
                        if (formatIp.equals(address.getHostAddress())) {
                            breakFlg = true;
                            break;
                        }
                    }

                    if (breakFlg) {
                        break;
                    }
                } catch (Exception e) {
                    logger.warn(e.getMessage());
                }

                Thread.sleep(3000);
            }
        }

        return updateFlag;
    }

    private static String formatIpv6IP(String ipV6Addr) {
        String strRet = ipV6Addr;
        StringBuffer replaceStr;
        int iCount = 0;
        char ch = ':';
       
        if (StringUtils.isNotEmpty(ipV6Addr) && ipV6Addr.indexOf("::") > -1) {
            for (int i = 0; i < ipV6Addr.length(); i++) {
                if (ch == ipV6Addr.charAt(i)) {
                    iCount++;
                }
            }

            if (ipV6Addr.startsWith("::")) {
                replaceStr = new StringBuffer("0:0:");
                for (int i = iCount; i < 7; i++) {
                    replaceStr.append("0:");
                }
            } else if (ipV6Addr.endsWith("::")) {
                replaceStr = new StringBuffer(":0:0");
                for (int i = iCount; i < 7; i++) {
                    replaceStr.append(":0");
                }
            } else {
                replaceStr = new StringBuffer(":0:");
                for (int i = iCount; i < 7; i++) {
                    replaceStr.append("0:");
                }
            }
            strRet = ipV6Addr.trim().replaceAll("::", replaceStr.toString());
        }
       
        return strRet;
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值