访问“〜” (用户主页)来自Linux中的Java [英] Accessing "~" (user home) from Java in Linux

查看:185
本文介绍了访问“〜” (用户主页)来自Linux中的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在〜/ .config / myapp.cfg中创建一个配置文件所以我这样做是用文件

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)

我尝试将路径更改为/ home / user之类的东西并且有效。所以我设法得出结论,java在foldername之前不知道什么是〜/表示什么是punct(。),因为/home/user/.config也不起作用。

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.

我该怎么办?

推荐答案

表示法是一个shell的东西。阅读外壳扩展

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

Java不理解这种表示法。要获取主目录,请获取系统属性 key user.home

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

(作为奖励,它也适用于Windows机器; - )

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

这篇关于访问“〜” (用户主页)来自Linux中的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆