用Java修改Window或者Linux下的hosts檔案
阿新 • • 發佈:2019-02-20
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;
}