How to create directory with a path that works for any OS?

11

I'm doing a job in Java and I need my program to create a directory in the user's home folder, but it needs to be able to create both Linux and Windows. Is it possible to create a "generic" path for this?

    
asked by anonymous 02.12.2014 / 23:58

1 answer

11

To get the user's home just use:

System.getProperty("user.home")

For creating and using directories you do not import the platform you do the same thing:

File arquivo = new File("/dir/arquivo.ext");
Path dir = Paths.get("/dir/sub");

Even in Windows you can use this way, the API will take care of solving.

You'll probably want to do something like this:

boolean ok = new java.io.File(System.getProperty("user.home"), "seudir").mkdirs();

I placed GitHub for future reference .

Documentation for mkdirs() .

You may prefer to use mkdir() in other cases. The difference for mkdirs() is that the first does not create anything in non-existent directories. The second one probably will not make a difference because you just got the path from the system. Although unlikely it is possible to have race condition and soon after to get the user.home it ceases to exist, with mkdir() will fail, with mkdirs() it will be re-created. You choose what you prefer in an extreme situation like this.

    
03.12.2014 / 00:09