Java - 使用 System.getProperty("user.dir") 获取主目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24709769/
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
Java - using System.getProperty("user.dir") to get the home directory
提问by joe
I was wondering if using:
我想知道是否使用:
System.getProperty("user.dir");
to get the absolute path of a folder is the best way to go about it? I am looking to pass my application onto other computers and I need a full proof way of getting the 'home' directory so that I can just add onto the path when I need to use other folders by just doing:
获取文件夹的绝对路径是最好的方法吗?我希望将我的应用程序传递到其他计算机上,我需要一种获取“主”目录的完整证明方式,以便在需要使用其他文件夹时只需执行以下操作即可添加到路径中:
String path = System.getProperty("user.dir");
String otherFolder = path + "\other";
回答by Jigar Joshi
way of getting home directory of current user is
获取当前用户主目录的方法是
String currentUsersHomeDir = System.getProperty("user.home");
and to append path separator
并附加路径分隔符
String otherFolder = currentUsersHomeDir + File.separator + "other";
The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.
系统相关的默认名称分隔符,为方便起见表示为字符串。该字符串包含单个字符,即separatorChar。
回答by Evan Sebastian
"user.dir" is the current working directory, not the home directory It is all described here.
“user.dir”是当前工作目录,不是home目录,这里都有说明。
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Also, by using \\
instead of File.separator, you will lose portability with *nix system which uses /
for file separator.
此外,通过使用\\
File.separator 代替,您将失去/
用于文件分隔符的*nix 系统的可移植性。
回答by Chetna Mishra
Program to get the current working directory=user.dir
获取当前工作目录的程序=user.dir
public class CurrentDirectoryExample {
public static void main(String args[]) {
String current = System.getProperty("user.dir");
System.out.println("Current working directory in Java : " + current);
}
}