SwitchHosts 换github-host 需要下载exe
解决方案
使用Java编写方法
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class HostChanger {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(
new TimerTask() {
public void run() {
HostChanger changer = new HostChanger();
changer.changeHost();
}
},
0,
60 * 60 * 1000);
}
public static String localhost = "C:\\Windows\\System32\\drivers\\etc\\hosts";
public static String localhostgithub = localhost ;
public static String githubhost = "https://raw.hellogithub.com/hosts";
public static void changeHost() {
try {
List<String> strings = readLines(localhost);
strings.addAll(github520());
File file = new File(localhostgithub);
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(localhostgithub));
strings.forEach(
string -> {
try {
bw.write(string);
bw.newLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
bw.close();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("Hosts changed");
}
public static List<String> readLines(String fileName) throws IOException {
List<String> lines = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("# GitHub520 Host Start")) {
while ((line = reader.readLine()) != null) {
if (line.startsWith("# GitHub520 主机端")) {
break;
}
}
} else {
lines.add(line);
}
}
reader.close();
return lines;
}
public static List<String> github520() throws Exception {
List<String> lines = new ArrayList<>();
URL url = new URL(githubhost);
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "curl/7.64.1");
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
lines.add(line);
}
}
reader.close();
return lines;
}
}
上面代码在做一个 bat程序 美哉
@echo off
@REM javaw HostChanger 后台运行
javac -encoding UTF-8 HostChanger.java
java HostChanger
@pause
有些类可以自己注释掉