Replacing the Host file in Java

只谈情不闲聊 提交于 2019-12-11 12:47:52

问题


So here's my code so far, yes I know it's pretty basic. But what I would Like to accomplish is to Replace the host file located in the System32\drivers\etc folder, the problem I am having in doing this is that I am getting an access denied error. How can I give the program access to make changes within the windows folder, also the class SaveURL just downloads the file and uses two strings to pass the name and download location through the function saveImage. How can I give myself access? Thanks in advance I truly appreciate it.

private void jButton7MouseClicked(java.awt.event.MouseEvent evt) {                                      
        String destinationHosts = "hosts";
        String urlHosts = "https://dl.dropbox.com/s/awdvoprxyo7r2q6/hosts?dl=1";
        Object hostOptions[] = {"Replace", "Close"};
        File fileHosts = new File(destinationHosts);
        File dirHost = new File("hosts");
        boolean dirHosts = dirHost.mkdir();
        try {
            Runtime.getRuntime().exec("notepad.exe \\Windows\\system32\\drivers\\etc\\hosts");
            jTextArea2.append("Opening Host File \n");
            int hostFile = JOptionPane.showOptionDialog(rootPane, "Would you like to replace the Hosts File?",
                    "Yes or No", JOptionPane.YES_NO_OPTION, JOptionPane.NO_OPTION, null, hostOptions, hostOptions[0]);
            if (hostFile == JOptionPane.YES_NO_OPTION) {
                jTextArea2.append("Downloading New Host File");
                SaveUrl.saveImage(urlHosts, destinationHosts);
                fileHosts.renameTo(new File(dirHost, fileHosts.getName()));
                Path source = Paths.get("\\hosts\\hosts");
                Path target = Paths.get("\\Windows\\system32\\drivers\\etc\\");
                Files.copy(source, target);
                jTextArea2.append("Host file replaced");
            }
        } catch (IOException ex) {
            Logger.getLogger(ToolKit1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }      

来源:https://stackoverflow.com/questions/13736684/replacing-the-host-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!