java - 获取本地应用数据目录路径的跨平台方式是什么?

标签 java cross-platform

我需要的是一种独立于平台的方式来获取本地应用程序数据目录的路径。 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/

相关文章:

java - GCP数据流流模板: Not able to customize google provided java based PubSubToBQ template

java - 使用 Java ResultSet 选择多个列值

java - 如何将数据更新到主存?

java - 在 play-framework 中获取 json

c++ - 跨平台 unicode 路径处理

java - 如何用Java编写文件列表

c++ - 如何在 windows 7/visual studio 2008 下为 windows XP 编译

c++ - Lua 是游戏服务器的最佳/最快选择吗?

c++ - c++ 中的逻辑 AND + 赋值,安全吗?

wpf - 为什么要在 XAML Window.Loaded 调用的方法中运行代码?