Java – 使用System.getProperty(“user.dir”)获取主目录

我想知道是否使用:

System.getProperty("user.dir"); 

获取文件夹的绝对路径是最好的方法吗? 我希望将我的应用程序传递到其他计算机上,我需要一个完整的certificate方式来获取’home’目录,以便我可以在我需要使用其他文件夹时添加到路径上:

 String path = System.getProperty("user.dir"); String otherFolder = path + "\\other"; 

获取当前用户的主目录的方式是

 String currentUsersHomeDir = System.getProperty("user.home"); 

并附加路径分隔符

 String otherFolder = currentUsersHomeDir + File.separator + "other"; 

File.separator

系统相关的默认名称分隔符,为方便起见,表示为字符串。 该字符串包含单个字符,即separatorChar。

“user.dir”是当前工作目录,而不是主目录。这里全部描述。

http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

此外,通过使用\\而不是File.separator,您将失去使用/用于文件分隔符的* nix系统的可移植性。

程序获取当前工作目录= 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); } }