문제

How can I get the location of the hosts file when using my application on different platforms?

도움이 되었습니까?

해결책

think that you would have to roll your own here I'm afraid, as this is a pretty low level system function, I think that it's a little beyond what you could expect java to do for you.

This link points to some special options that you can set to alter the bind order, I don't think that they will tell you where the hosts file is, but you could could investigate in and around these options to see if you can find anything else to help you

다른 팁

You could use the "os.name" system property to determine the operating system. Then, retrieve the hosts file depending on where each operating system stores it. For example:

String osName = System.getProperty("os.name").toLowerCase();
File hostsFile;
if (osName.startsWith("mac os x")){
  hostFile = new File("/etc/hosts");
} else if (osName.contains("windows")){
  hostFile = //...
}

Take a look at the hosts file locations for each operating system and version on Wikipedia. Unfortunately you will have to implement your own logic similar to Michael's answer:

import java.awt.Desktop;
import java.io.File;

public class HostsFile
{
    public static void main(String[] args) throws Exception
    {
        String osName = System.getProperty("os.name");

        File hostsFile = null;

        if (osName.contains("Windows"))
        {
            hostsFile = new File(System.getenv("WinDir")
                    + "\\system32\\drivers\\etc\\hosts");
        }

        Desktop.getDesktop().open(hostsFile);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top