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

Asked

Viewed 5,489 times

13

I am 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 in Linux and Windows. It is possible to create a "generic" path for such?

  • What is the use of the directory for? In this case there would be the possibility of creating a package in Java and thus storing the files?

1 answer

13


To get the user’s "home" just use:

System.getProperty("user.home")

For the creation and use of directories no matter the platform you do the same:

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 probably want to do something like this:

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

I put in the Github for future reference.

Documentation of mkdirs().

You may prefer to use mkdir() in other cases. The difference to the mkdirs() is that the first one creates nothing in non-existent directories. The second one probably won’t matter because it just received the path system. Although unlikely it is possible to exist a race condition and soon after to catch the user.home it cease to exist, with the mkdir() will fail, with the mkdirs() it will be created again. You choose what you prefer in such an extreme situation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.