windows Java:System.getenv("APPDATA") 返回 null,现在怎么办?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5765181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:42:25  来源:igfitidea点击:

Java: System.getenv("APPDATA") returns null, now what?

javawindows

提问by python dude

I just found out that when a Java program is launched on Windows via "Run As..." (from the executable's context menu) as a different user, a call to System.getenv("APPDATA")will return null, rather than the usual application data folder.

我刚刚发现,当 Java 程序通过“运行方式...”(来自可执行文件的上下文菜单)作为不同的用户在 Windows 上启动时,调用System.getenv("APPDATA")将返回null,而不是通常的应用程序数据文件夹。

Now, I'm kind of a noob when it comes to Windows folders and such, so my question is, how should I deal with this situation when my program has to be able to store its data somewhere in order to work correctly? More specifically, if System.getenv("APPDATA")returns null, am I even allowedto store any data at all, and if so, where? Thanks in advance!

现在,当涉及到 Windows 文件夹等时,我有点菜鸟,所以我的问题是,当我的程序必须能够将其数据存储在某处才能正常工作时,我应该如何处理这种情况?更具体地说,如果System.getenv("APPDATA")回报null,我会甚至允许在所有存储任何数据,如果是这样,在哪里?提前致谢!

采纳答案by python dude

Okay, I solved my own problem using JNA:

好的,我使用 JNA 解决了我自己的问题:

com.sun.jna.platform.win32.Shell32Util.getFolderPath(int nFolder)

where nFolder = 0x001afor the application data folder and nFolder = 0x001cfor the local application data folder. On Windows XP, the output is

其中nFolder = 0x001a用于应用程序数据文件夹和nFolder = 0x001c本地应用程序数据文件夹。在 Windows XP 上,输出为

C:\Documents and Settings\[UserName]\Application Data

C:\Documents and Settings\[UserName]\Local Settings\Application Data

C:\Documents and Settings\[用户名]\Application Data

C:\Documents and Settings\[用户名]\Local Settings\Application Data

Most importantly, this does not return nullwhen the program is launched via Run As.

最重要的是,null当程序通过Run As.

回答by Suzanne

Also if you set an environment variable in windows, I noticed that java doesn't pick it up until I restarted the OS.

此外,如果您在 Windows 中设置了环境变量,我注意到在我重新启动操作系统之前,java 不会选择它。

回答by Harry Joy

Yes you are always allowed to store data. You can use temp directoryto store you data. You can get temp directory by System.getProperty("java.io.tmpdir");.

是的,您始终可以存储数据。您可以使用临时目录来存储您的数据。您可以通过System.getProperty("java.io.tmpdir");.