Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file

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?

like image 822
artouiros Avatar asked Sep 18 '11 18:09

artouiros


People also ask

How do I find my home path in Linux?

To navigate to your home directory, use "cd" or "cd ~" To navigate up one directory level, use "cd .." To navigate to the previous directory (or back), use "cd -" To navigate through multiple levels of directory at once, specify the full directory path that you want to go to.

How do I see other users home directory in Linux?

Find User's Home Directory Using Cd Command Executing the cd (change directory) command alone should take you to the home directory of the current Linux user.

What is the home directory of a user in Linux?

A home directory is the directory or folder commonly given to a user on a network or Unix or Linux variant operating system. With the home directory the user can store all their personal information, files, login scripts, and user information.

How do I get to the users directory in Linux?

On Linux it's often /home/user. However, on some OS's, like OpenSolaris for example, the path is /export/home/user.


1 Answers

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 ;-)

like image 94
aioobe Avatar answered Sep 18 '22 19:09

aioobe