在Java中以编程方式设置Linux环境变量 [英] Set Linux environment variable programmatically in Java

查看:273
本文介绍了在Java中以编程方式设置Linux环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够通过RunTime类运行Linux命令. 有没有办法通过Java从Java设置Linux全局环境?

I am able to run a Linux command via RunTime class. Is there a way of setting a Linux global enviroment from Java programatically?

我想通过Java模拟以下Linux命令语句

I want to emulate the following Linux command statement over Java

root@machine:/tmp# export TEST=v2

我已按以下方式使用ProcessBuilder,但TEST变量未更改.

I have used ProcessBuilder as following, but TEST variable does not changed.

ProcessBuilder pb = new ProcessBuilder("/bin/bash","-c","export TEST=v3" + "&& exec");

更新: 实际上,我的最终目标是使用EMAIL_NAME环境作为电子邮件地址,当我的应用程序和计算机都启动和停止时,这些操作将发送到EMAIL_NAME. 在那种情况下,我知道不可能在纯Java代码上设置linux全局环境.因此,我有一个解决方法,就是将EMAIL_NAME保留在一个文件中,并通过linux脚本或Java代码对其进行更新或读取.

UPDATE: Actually my ultimate target is to use EMAIL_NAME enviroment as an email address, when both my application and machine are started and stopeed these actions will be sent to EMAIL_NAME. In that case I understand that it is not possible to set linux global enviroment over pure Java code. So I have a workaround solution is that EMAIL_NAME will be hold in a file and it will be updated or read by linux script or java code.

推荐答案

环境变量(设置后)仅适用于设置了该变量的进程所产生的进程,因此,如果您真的要设置一个会影响整个系统,然后不会.您根本无法在Linux中以交互方式真正做到这一点.最好的办法是更改系统启动文件之一,使其包含上述变量,以便您在未来中执行的任何操作都将包含该变量.

Environment variables, when set, are only available to processes spawned by the process where the variable is set, so if you're really asking to set a variable that will affect the entire system, then no. You can't really do that at all in Linux interactively. The best you could do is alter one of the system startup files to include said variable so that anything you do in the future would include that variable.

如果您只是想运行带有某些变量集的多个进程,则 ProcessBuilder 允许您

If you're simply looking to run several processes with some variable set, then ProcessBuilder allows you to set an environment for processes spawned with it. Reusing an environment for several processes is pretty trivial with that.

这篇关于在Java中以编程方式设置Linux环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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