在Java中使用导出 [英] Using export in Java

查看:125
本文介绍了在Java中使用导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  SOME_VARIABLE = / home / .. 
export SOME_VARIABLE

如何使用java设置此变量,以便我可以在不只一台机器上使用这个程序吗?基本上我想通过java模拟上述命令。

解决方案

使用<$ c $时可以设置环境变量c> java.lang.Runtime.getRuntime()。exec(...)或 java.lang.Processbuilder 调用其他程序。



使用Processbuilder,您可以执行以下操作:

  ProcessBuilder processBuilder = new ProcessBuilder(你的命令); 
processBuilder.environment()。put(SOME_VARIABLE,/ home / ..);
processBuilder.start();

使用运行时,它是:

 映射< String,String> environment = new HashMap< String,String>(System.getenv()); 
environment.put(SOME_VARIABLE,/ home / ..);
String [] envp = new String [environment.size()];
int count = 0;
for(Map.Entry< String,String> entry:environment.entrySet()){
envp [count ++] = entry.getKey()+=+ entry.getValue();
}

Runtime.getRuntime()。exec(你的命令,envp);


I am using java to call another program which relies on an exported environment variable to function:

SOME_VARIABLE=/home/..
export SOME_VARIABLE

How can I use java to set this variable, so that I can use this program on more than just one machine? Essentially I want to be able to emulate the above commands via java.

解决方案

You can set environment variables when using java.lang.Runtime.getRuntime().exec(...) or java.lang.Processbuilder to call the other program.

With Processbuilder, you can do:

ProcessBuilder processBuilder = new ProcessBuilder("your command");
processBuilder.environment().put("SOME_VARIABLE", "/home/..");
processBuilder.start();

With Runtime, it's:

Map<String, String> environment = new HashMap<String, String>(System.getenv());
environment.put("SOME_VARIABLE", "/home/..");
String[] envp = new String[environment.size()];
int count = 0;
for (Map.Entry<String, String> entry : environment.entrySet()) {
    envp[count++] = entry.getKey() + "=" + entry.getValue();
}

Runtime.getRuntime().exec("your command", envp);

这篇关于在Java中使用导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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