我需要的是一种独立于平台的方式来获取本地应用程序数据目录的路径。 System.getenv("LOCALAPPDATA")
似乎只适用于 Windows。我该怎么办?
最佳答案
你可能会说类似(如果我错了,或者如果这是一个不好的方法,请反驳我)
private String workingDirectory;
//here, we assign the name of the OS, according to Java, to a variable...
private String OS = (System.getProperty("os.name")).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
else
{
//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
//folder.
请注意,在这段代码中,我充分利用了 Java 在处理目录时将 '/'
与 '\\'
相同的处理方式。 Windows 使用 '\\'
作为 pathSeparator,但它也对 '/'
感到满意。 (至少 Windows 7 是。)它的环境变量也不区分大小写;我们可以很容易地说 workingDirectory = System.getenv("APPDATA");
并且效果也一样。
关于java - 获取本地应用数据目录路径的跨平台方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11113974/