I need to create a configuration file in开发者_C百科 ~/.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?
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 ;-)
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");
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();
}
精彩评论