java - 如何获得本地应用数据目录路径的跨平台方法?

63 4

我需要一个独立的平台来获取本地应用程序数据目录的路径。System.getenv("LOCALAPPDATA") 似乎只适用于 Windows 。我该怎么做?


94 3

你可以能会说( 如果我是错误的,或者者是不好的方法的话) 。

private String workingDirectory;
//here, we assign the name of the OS, according to Java, to a variable...
private String OS = (System.getProperty("")).toUpperCase();
//to determine what the workingDirectory is.
//if it is some version of Windows
if (OS.contains("WIN"))
//it is simply the location of the"AppData" folder
 workingDirectory = System.getenv("AppData");
//Otherwise, we assume Linux or Mac
//in either case, we would start in the user's home directory
 workingDirectory = System.getProperty("user.home");
//if we are on a Mac, we are not done, we look for"Application Support"
 workingDirectory +="/Library/Application Support";
//we are now free to set the workingDirectory to the subdirectory that is our 

注意,在这段代码中,我充分利用了Java在处理目录时将 '/' 视为 ''的充分优势。Windows 使用 '' 作为,但它对 '/' 也很满意。( 至少 Windows 7是。) 它也不区分大小写,我们可以以轻松地说明。workingDirectory = System.getenv("APPDATA");而且它也会工作得很好。