如何动态修改windows下的host文件
发布时间:2020-12-15 06:39:41 所属栏目:Java 来源:网络整理
导读:事件背景:为了测试数据提交后,需要在另一个环境的多个测试节点下去验证测试数据是否添加成功,找了一大堆放法,用了比较笨的方法实现了。不多废话思路如下: 为了万无一失,先备份hosts文件内容: 1.读取hosts所有文本内容,代码如下 /** * 获取文件全部内
事件背景:为了测试数据提交后,需要在另一个环境的多个测试节点下去验证测试数据是否添加成功,找了一大堆放法,用了比较笨的方法实现了。不多废话思路如下: 为了万无一失,先备份hosts文件内容: 1.读取hosts所有文本内容,代码如下 /** * 获取文件全部内容 * @param fileName * @return */ public String readToString(String fileName) { String encoding = "UTF-8"; File file = new File(fileName); Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } (IOException e) { e.printStackTrace(); } { return String(filecontent,encoding); } (UnsupportedEncodingException e) { logger.error("The OS does not support " + encoding); e.printStackTrace(); null; } } 2.清空hosts文件内容: * 清空文本内容 * fileName public void clearInfoForFile(String fileName) { File file = File(fileName); if(!file.exists()) { file.createNewFile(); } FileWriter fileWriter = FileWriter(file); fileWriter.write(""); fileWriter.flush(); fileWriter.close(); } (IOException e) { e.printStackTrace(); } } ? 3.追加一行hosts,也可以多个,视情况写入 * 在已有的文件后面追加信息 * info appendInfoToFile(String fileName,String info) { File file =file.exists()){ file.createNewFile(); } FileWriter fileWriter =new FileWriter(file,true); fileWriter.write(info); fileWriter.flush(); fileWriter.close(); } (IOException e) { e.printStackTrace(); } } 4.打开hosts绑定网站,这里我们以百度为例,提示无法连接。 5.在清空hosts文件,将备份的原内容写入即可完成还原hosts文件操作 6.测试代码如下: @Test run(){ String hosts =readToString("C:/Windows/System32/drivers/etc/hosts"); clearInfoForFile("C:/Windows/System32/drivers/etc/hosts"); appendInfoToFile("C:/Windows/System32/drivers/etc/hosts","127.0.0.1 www.baidu.com"); System.setProperty("webdriver.chrome.driver","tools/chromedriver.exe"); WebDriver driver= ChromeDriver(); driver.get("https://www.baidu.com/"); { Thread.sleep(5); } (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } clearInfoForFile("C:/Windows/System32/drivers/etc/hosts"); appendInfoToFile("C:/Windows/System32/drivers/etc/hosts",hosts); } 笨方法实现,先Mark下。 ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Java导入导出Excel工具类ExcelUtil
- java – ConcurrentModificationException的幻数
- java – 使用ThreadPoolExecutor的活动任务数
- java – 日历卷影响其他日历
- Java使用Redis实例
- 【SpringBoot】14. SpringBoot多环境配置
- java – Eclipse – 基于return或get(Shortcut)声明变量
- Struts2 ActionContext.getContext().get(Object key)法:获
- Java遍历输出指定目录、树形结构所有文件包括子目录下的文件
- java – 为什么不在启用夏令时的情况下运行服务器端应用程序