mis*_*tor 42 java cross-platform
我需要的是一种独立于平台的获取本地应用程序数据目录路径的方法.System.getenv("LOCALAPPDATA")似乎只适用于Windows.我该怎么做?
Mik*_*ren 36
你可能会说些什么(如果我错了,或者这是一个糟糕的方法,我会反驳)
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.
Run Code Online (Sandbox Code Playgroud)
请注意,在此代码中,我充分利用了Java '/'与'\\'处理目录时相同的处理方式.Windows '\\'用作pathSeparator,但它也很满意'/'.(至少Windows 7是.)它的环境变量也不区分大小写; 我们可以很容易地说workingDirectory = System.getenv("APPDATA");,它也会起作用.
kir*_*gin 15
就个人而言,我发现appdirs对类似的用例非常有帮助.它具有定位不同类型的有用目录的功能:
getUserDataDirgetUserConfigDirgetUserCacheDirgetUserLogDirgetSiteDataDir ←看起来这是你需要的getSiteConfigDir它返回的位置或多或少是标准的:
Fjo*_*rak 10
任务已经过时,但我错过了一个回答列表环境变量,而不是一些有趣的绝对路径.我对OSX一无所知.这篇文章只包含有关Windows和Linux的信息.
我没有足够的积分来扩展现有的答案,所以我必须写一个新答案.
Linux: 如前所述,存在类似freedesktop.org的东西,它定义了linux发行版试图实现的标准.还有一个子页面定义环境变量及其默认值(如果未设置它们,则默认为空.应用程序必须将变量与默认值匹配).链接到该页面:freedesktop.org env vars
Vars定义与此问题相关:
Windows XP:
%APPDATA%(默认为:C:\ Documents and Settings {username}\Application Data)
%CommonProgramFiles%(默认为:C:\ Program Files\Common Files)(共享程序文件)
%CommonProgramFiles(x86)%(默认为:C:\ Program Files(x86)\ Common Files)(仅限64位!)(共享程序文件)
%ProgramFiles%(默认为:%SystemDrive%\ Program Files)
%ProgramFiles(x86)%(默认为:%SystemDrive%\ Program Files(x86)(仅限64位版本))(仅限64位!)
Windows Vista +:
%CommonProgramFiles(x86)%(默认为:C:\ Program Files(x86)\ Common Files)(仅限64位!)(共享程序文件)
%ProgramFiles%(默认为:%SystemDrive%\ Program Files)(安装后不会更改的静态数据)
%ProgramFiles(x86)%(默认为:%SystemDrive%\ Program Files(x86)(仅限64位版本))(仅限64位!)(安装后不会更改的静态数据)
%ProgramData%(默认为:%SystemDrive%\ ProgramData)(影响所有用户的可变数据)
简而言之: Linux有两个可能未设置的环境变量(一个用于配置,一个用于文件).据我所知,Windows只能将一个环境变量用于配置和文件.请使用这些而不是绝对路径.
| 归档时间: |
|
| 查看次数: |
21264 次 |
| 最近记录: |