以独立于平台的方式将环境变量传递给 JVM
我正在开发一个 J2EE 应用程序,该应用程序在 Windows Vista 计算机上的 JBoss 中运行,但该应用程序最终将在 Linux 计算机上运行。有没有一种方法可以以独立于平台的方式传递环境变量的值?
我认为(但我不确定)平台敏感的方式是:
-Denv_var=%MY_ENV_VAR% (Windows)
-Denv_var=$MY_ENV_VAR (Linux)
从那里我将使用
System.getProperty("MY_ENV_VAR");
- 这是正确的吗?
System.getenv(String name)
的 Javadoc 似乎暗示该方法依赖于平台,但我对此并不清楚。我可以完全跳过将变量传递到 JVM 中,并在使用操作系统设置环境变量的值后使用 getenv() 吗?
I'm developing a J2EE application that runs in JBoss on a Windows Vista machine, but the application will end up on a Linux machine. Is there a way to pass in the value of an environment variable in a platform independent way?
I think (but I'm not sure) the platform-sensitive way would be:
-Denv_var=%MY_ENV_VAR% (Windows)
-Denv_var=$MY_ENV_VAR (Linux)
and from there I would access the value (in Java) using
System.getProperty("MY_ENV_VAR");
— is that correct?
The Javadoc for System.getenv(String name)
seem to imply that method is platform-dependent, but I'm not clear on that. Could I just skip passing the variable into the JVM completely, and use getenv()
after using setting the value for an environment variable using the OS?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
System.getenv()本身是平台无关的。使用上面的示例,您肯定可以编写
并且它可以在 Linux 和 Windows 上运行。没有理由将其包装到 java 系统属性中。也就是说,getenv() 的“平台相关”部分在于不同的操作系统使用不同的环境变量,例如 Windows 上的 PATH 与 Linux 上的路径。但只要您使用自己的变量并一致地命名它们(例如,始终大写),就可以了。
System.getenv() is platform-independent by itself. Using your above example, you can most certainly write
and it will work on both Linux and Windows. No reason to wrap this into java system property. That said, the "platform-dependent" part of
getenv()
lies in the fact that different operating systems use different environment variables, like PATH on windows vs path on Linux. But as long as you're using your own variables and name them consistently (always uppercase, for example), you'll be fine.我如何解释关于此的java教程是getenv 以独立于平台的方式工作,但您必须记住变量在跨平台上的命名不一致。由于您似乎自己设置了 var,因此这不适用于您。
How I interpret the java tutorial on this is that getenv works in a platform independent way, but that you have to keep in mind that variables are not consistently named across platforms. Since you seem to set the var yourself, this does not apply to you.
是的 - getEnv() 将只返回环境变量的名称,您可以以适合您正在运行的平台的任何方式设置它(通常通过 Win32 上的启动批处理文件)。如果可能您想避免让用户感到混乱,最好根据平台使用合理的默认值(通过检查 System.getProperty("os.name"))使用环境变量来运行您的软件。
Yes - getEnv() will just return the name of the environment variable, and you can set it in whatever way is appropriate to the platform you're running on (typically via a launch batch file on Win32). It's good practice to fall back on sensible defaults based on the platform (by inspecting
System.getProperty("os.name")
), if it's possible you want to avoid having your users bother with needing to mess with environmental variables to run your software.