Question

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

Was it helpful?

Solution

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

OTHER TIPS

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top