每个执行脚本的机器设置不同,造成脚本在不同的机器上执行效果不尽相同。因此提出了自动化脚本的初始化这个概念。
初始化模块中有一个需求,要将脚本执行机的HOST标准化,令浏览器的运行环境一致。
对HOST的操作,分三步,在脚本执行前,先备份当前HOST文件,然后重写生成HOST文件,脚本执行完成后,从备份恢复机器的原有HOST文件。
以下代码通过java.io实现了三个功能:写HOST文件(hostSet)、备份HOST文件(hostBak)、从BAK恢复HOST文件(hostRestore)。
package tools;
import java.io.*;
public class Host {
public static void hostSet() {
try {
File file = new File("C://Windows//System32//drivers//etc//hosts");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();// 测试系统1
bw.write("111.111.111.111 test1.com");
bw.newLine();// 测试系统2
bw.write("222.222.222.222 test2.com");
bw.newLine();// 测试系统3
bw.write("333.333.333.333 test3.com");
//………………
bw.newLine();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void hostBak() {
try {
FileInputStream inFile = new java.io.FileInputStream(
"C://Windows//System32//drivers//etc//hosts");
FileOutputStream outFile = new FileOutputStream(
"C://Windows//System32//drivers//etc//hostsbak");
byte[] bt = new byte[1024];
int count;
while ((count = inFile.read(bt)) > 0) {
outFile.write(bt, 0, count);
}
inFile.close();
outFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void hostRestore() {
try {
FileInputStream inFile = new java.io.FileInputStream(
"C://Windows//System32//drivers//etc//hostsbak");
FileOutputStream outFile = new FileOutputStream(
"C://Windows//System32//drivers//etc//hosts");
byte[] bt = new byte[1024];
int count;
while ((count = inFile.read(bt)) > 0) {
outFile.write(bt, 0, count);
}
inFile.close();
outFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}