简体   繁体   English

从 java 代码设置本地 dos 变量

[英]set local dos variables from java code

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?如果从命令行运行“java -jar”,有没有办法从 java 程序设置本地 dos 变量,以便在退出 java 后,它仍然可以存在于同一个 Z21D6F40CFB011982E57424 中?

example例子

(cmd)
c:\java package.Class 

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

// java exited

echo %name%

value

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.让 Java 程序在某个已知位置写出一个批处理文件,然后调用它来设置变量。 Since batch files run in the current cmd process they can alter environment variables there.由于批处理文件在当前cmd进程中运行,因此它们可以在那里更改环境变量。
  • Let the program output name/value pairs or complete set commands, catch the output and set the variables yourself afterwards.让程序 output 名称/值对或完整的命令set ,捕获 output 并自行设置变量。 Goes wrong as soon as you want or have other output, I guess.我猜,只要你想要或有其他 output,就会出错。

It's possible to set environment variables, according to question 2121795 .根据问题 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).如果它们确实有效,请记住设置环境变量不会在当前 session 中生效(您需要重新启动 cmd 窗口)。

Also interesting is this question which has answers explaining how to use the Preferences API to modify the registry. 这个问题也很有趣,它的答案解释了如何使用 Preferences API 来修改注册表。 I guess you should be able to modify environment variables via this route (didn't check thorougly).我想你应该能够通过这条路线修改环境变量(没有仔细检查)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM