获取本地应用程序数据目录路径的跨平台方式是什么? [英] What is the cross-platform way of obtaining the path to the local application data directory?

查看:93
本文介绍了获取本地应用程序数据目录路径的跨平台方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的是一种与平台无关的获取本地应用程序数据目录路径的方法。 System.getenv(LOCALAPPDATA)似乎只适用于Windows。我该怎么做呢?

What I need is a platform-independent way of obtaining the path to the local application data directory. System.getenv("LOCALAPPDATA") seems to work only with Windows. How do I go about this?

推荐答案

你可能会说(如果我错了,或者如果这是坏方法)

You could probably say something like (contradict me if I am wrong, or if this a bad approach)

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); 并且它也可以正常工作。

Note that, in this code, I am taking full advantage that Java treats '/' the same as '\\' when dealing with directories. Windows uses '\\' as pathSeparator, but it is happy with '/', too. (At least Windows 7 is.) It is also case-insensitive on it's environment variables; we could have just as easily said workingDirectory = System.getenv("APPDATA"); and it would have worked just as well.

这篇关于获取本地应用程序数据目录路径的跨平台方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆