在 Linux 中从 Java 访问“~”(用户主页)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7463545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:05:03  来源:igfitidea点击:

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

javafile

提问by artouiros

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

我需要在 ~/.config/myapp.cfg 中创建一个配置文件所以我这样做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.

我尝试将路径更改为 /home/user 之类的内容,并且成功了。所以我设法得出一个结论,java 不知道 ~/ 是什么意思以及文件夹名之前的 punct(.) 是什么意思,因为 /home/user/.config 也不起作用。

What should I do?

我该怎么办?

回答by aioobe

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

~符号是一个shell的事情。阅读有关外壳扩展的信息

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

Java 不理解这种表示法。要获取主目录,请使用 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 ;-)

(作为奖励,它也可以在 Windows 机器上运行 ;-)

回答by fvu

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

用户user.home系统属性。为了完全避免操作系统依赖性,您应该让 File 进行路径解析,如下所示:

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

回答by Sandro Munda

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

~您应该使用(它也适用于 Windows)而不是直接使用快捷方式

System.getProperty("user.home");

Example :

例子 :

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