从java代码设置本地dos变量

发布于 2024-11-14 07:33:44 字数 264 浏览 6 评论 0原文

如果从命令行运行“java -jar”, 有没有办法从java程序设置本地dos变量,以便 java退出后,它仍然可以存在于同一个会话中吗?

例子

(cmd)
c:\java package.Class 

/*then in program you do something like 
'System.setVariable("name","value");'
*/

// java exited

echo %name%

value

If "java -jar" is run from a command line,
is there a way to set local dos variable from java program so that
after java is exited, it can still be present in the same session?

example

(cmd)
c:\java package.Class 

/*then in program you do something like 
'System.setVariable("name","value");'
*/

// java exited

echo %name%

value

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

感悟人生的甜 2024-11-21 07:33:44

不可以。进程不能修改其父进程的环境。

您能做的最好的事情就是稍微作弊并执行以下操作之一:

  • 让 Java 程序在某个已知位置写出一个批处理文件,然后调用它来设置变量。由于批处理文件在当前的 cmd 进程中运行,因此它们可以更改其中的环境变量。
  • 让程序输出名称/值对或完成 set 命令,捕获输出并随后自行设置变量。我猜,一旦你想要或有其他输出,就会出错。

No. Processes cannot modify their parents' environment.

The best thing you can do is cheat a little and do either of the following:

  • Let the Java program write out a batch file in some known location and call it afterwards to set variables. Since batch files run in the current cmd process they can alter environment variables there.
  • Let the program output name/value pairs or complete set commands, catch the output and set the variables yourself afterwards. Goes wrong as soon as you want or have other output, I guess.
简单 2024-11-21 07:33:44

根据问题 2121795,可以设置环境变量。但是,我从未尝试过这些方法,因此无法验证它们是否有效。

如果它们确实有效,请记住设置环境变量不会在当前会话中生效(您需要重新启动 cmd 窗口)。

It's possible to set environment variables, according to question 2121795. However, I've never tried these methods so can't verify if they work.

If they do work, remember that setting an environment variable will not take effect in the current session (you'd need to restart the cmd window).

无法回应 2024-11-21 07:33:44

同样有趣的是这个问题,它的答案解释了如何使用首选项修改注册表的API。我想你应该能够通过这条路线修改环境变量(没有彻底检查)。

Also interesting is this question which has answers explaining how to use the Preferences API to modify the registry. I guess you should be able to modify environment variables via this route (didn't check thorougly).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文