首页 > 编程语言 >host 工具类-Java

host 工具类-Java

时间:2022-12-13 09:56:22浏览次数:74  
标签:return String ip host static import Java 工具

/*
 * Copyright (C) 2022 www.mobaijun.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mobaijun.common.util.system;

import cn.hutool.core.io.FileUtil;
import com.mobaijun.common.constant.JdkConstant;
import com.mobaijun.common.util.collection.CollectionUtil;
import com.mobaijun.common.util.text.Charsets;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * software:IntelliJ IDEA 2022.2.3<br/>
 * class name: HostUtil<br/>
 * class description: host 工具类<br/>
 * > Linux 下和 Mac Os 待完善
 * 如果遇到 host 文件没有权限写入,请先右键host文件 -> 安全 -> 当前用户 -> 编辑 -> 当前用户 -> 勾选完全控制,如下图<br/>
 * <img src="https://tencent.cos.mobaijun.com//xxbj_img/image-20221210004329990.png"/>
 *
 * @author MoBaiJun 2022/12/9 23:15
 */
public class HostUtil {

    /**
     * Windows host file path
     */
    private static final Path WIN_HOSTS_PATH = Paths.get("C:\\Windows\\System32\\drivers\\etc\\hosts");

    /**
     * linux host file path
     */
    private static final Path LINUX_HOSTS_PATH = Paths.get("/etc/hosts");

    /**
     * Windows
     */
    private static final String WINDOWS = "Windows";

    /**
     * Windows flush dns
     */
    private static final String FLUSH_DNS = "ipconfig /flushdns";

    /**
     * Line break character
     */
    private static final String END = String.format("%n");


    /**
     * 获取操作系统类型返回 host 文件地址
     *
     * @return host 文件地址
     */
    public static String getOsName() {
        String osName = java.lang.System.getProperty(JdkConstant.OS_NAME);
        if (WINDOWS.regionMatches(1, osName, 1, 1)) {
            return WIN_HOSTS_PATH.toString();
        }
        return LINUX_HOSTS_PATH.toString();
    }


    /**
     * 读取 host 文件内容
     *
     * @return list 集合
     */
    public static List<String> readHosts() {
        return FileUtil.readLines(getOsName(), Charsets.UTF_8)
                .stream()
                .filter(it -> !it.trim().matches("(^#.*)|(\\s*)"))
                .map(it -> it.replaceAll("#.*", "").trim()
                        .replaceAll("\\s+", "\t"))
                .collect(Collectors.toList());
    }


    /**
     * 追加写入 host
     *
     * @param ip  IP 地址
     * @param url 映射地址
     * @return 是否成功
     */
    public static boolean append(String ip, String url) {
        // 存在返回 false
        if (exists(ip, url)) {
            return false;
        }
        List<String> sets = CollectionUtil.newArrayList();
        sets.add(String.format("%s\t%s", ip, url));
        return FileUtil.appendUtf8Lines(sets, getOsName()).exists() && flushDns();
    }

    /**
     * 当前 IP 地址是否存在 host 文件中
     *
     * @param ip  IP 地址
     * @param url 映射地址
     * @return 是否存在
     */
    public static boolean exists(String ip, String url) {
        return readHosts().contains(String.format("%s\t%s", ip, url));
    }

    /**
     * 刷新 dbs
     *
     * @return 是否成功
     */
    public static boolean flushDns() {
        try {
            Runtime.getRuntime().exec(FLUSH_DNS);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

源码地址传送门

标签:return,String,ip,host,static,import,Java,工具
From: https://www.cnblogs.com/mobaijun/p/16977761.html

相关文章

  • 这款工具火了!自媒体一键图文转视频工具!
    这款工具可一键生成相应配音,自动匹配图片动图、进行校对,生成视频,制作完成的视频可直接上传到自媒体平台。这让小黑瞬间来了兴趣马上就打开文章试了试这是我随手找来的一......
  • ABP vNEXT-1安装ABP 官方提供的CLI工具
    1)、使用命令行窗口安装ABP官方提供的CLI工具,安装命令如下:dotnettoolinstall-gVolo.Abp.Cli,如下图所示:  2)、如果在创建过程中因为网络原因会连接失败的话,可以......
  • JAVA8 lambda之reduce三种用法
    reduce操作可以根据指定的计算模型,实现从Stream中生成一个指定类型的值。一,用法1未定义初始值,从而第一次执行的时候第一个参数m的值是Stream的第一个元素,第二个参数n是St......
  • 功能测试中数据库与抓包工具的作用
    功能测试中数据库与抓包工具的作用1:数据库的应用场景验证数据的准确性和完整性借助数据库尽情缺陷定位借助数据库构造测试场景(需要特定的测试数据)借助数据库备份与更新2......
  • 用 Java?试试国产轻量的 Solon v1.11.4(带视频)
    一个更现代感的Java应用开发框架:更快、更小、更自由。没有Spring,没有Servlet,没有JavaEE;独立的轻量生态。主框架仅0.1MB。@ControllerpublicclassApp{publ......
  • Java数据结构之栈和队列
    原文链接:https://blog.csdn.net/fear_wolf/article/details/127459611文章目录一、栈(Stack)(一)概念(二)栈的使用(三)栈的模拟实现(四)问题思考1.栈,虚拟机栈,栈帧有什么区别?2.单链......
  • 【JAVA笔记】Java中的常用工具API简介、Object类的特点、JavaBean类重写Object类中的
    一、Java常用工具API简介   根据步骤查找API文档使用对应功能API网址:https://www.apiref.com/java11-zh/index.html什么是API?二、Object类的特点1.java.lan......
  • java 数组实现队列
     算法题用数组实现队列,三个函数,分别是添加add(),出队poll()和获取队中的元素个数getSize()当队的元素满的时候进行二倍的扩容。classmyqueue{privateint[]date;......
  • 直播:Java架构师成长之线上问题排查,定位,分析与复盘 排查问题的方法 一般有用
    报错                                                   ......
  • Oracle-OSW性能监控工具
    参考:http://www.savedba.com/?p=591OSWatcherBlackBox,简称OSW,是oracle提供的一个小但是非常有用的工具,它通过调用OS自己提供的命令来记录OS运行时的一些性能参数,比如CPU......