artouiros
artouiros

Reputation: 3987

Accessing "~" (user home) from Java in Linux

I need to create a configuration file in ~/.config/myapp.cfg So I am doing this with File:

File f;
f = new File("~/.config/gfgd.gfgdf");
if(!f.exists()){
    f.createNewFile();
}

The problem is, that it tell me, that directory doesn't exist and something like this.

java.io.IOException: Not such file or directory
    at java.io.UnixFileSystem.createFileExclusively(Native Method)

I tried changing path to something like /home/user and it worked. So i managed to make a conclusion, that java doesn't know what ~/ means and what a punct(.) before foldername means too, because /home/user/.config doesn not work aswell.

What should I do?

Upvotes: 36

Views: 19211

Answers (3)

aioobe
aioobe

Reputation: 420990

The ~ notation is a shell thing. Read up on shell expansion.

Java doesn't understand this notation. To get hold of the home directory, get the system property with key user.home:

String home = System.getProperty("user.home");
File f = new File(home + "/.config/gfgd.gfgdf");

(As a bonus, it will work on windows machines too ;-)

Upvotes: 69

Sandro Munda
Sandro Munda

Reputation: 41030

Instead of using directly the ~ shortcut, you should use (it also works on Windows)

System.getProperty("user.home");

Example :

File f = new File(System.getProperty("user.home") + "/.config/gfgd.gfgdf");
if (!f.exists()) {
    f.createNewFile();
}

Upvotes: 4

fvu
fvu

Reputation: 32953

User the user.home System property. To completely avoid operating system dependencies you should let File do the path resolution, like this:

f = new File(new File (System.getProperty("user.home"),".config"),"gfgd.gfgdf");

Upvotes: 10

Related Questions