System.getenv(name) needs the name of environment variable.
I am trying to call Runtime.exec(String[], String[], File), the secondary parameter need an array of environment variable, I am not sure whether subprocess will inherit environment variables from current process if I specified this parameter.
For example, if I pass new String[]{"NEWDIR=/home"} as secondary parameter and current java process has environment OLDDIR=/var, what is the return value of System.getenv("OLDDIR") in the subprocess?
updated:
Sorry, I have to use Java 1.4 and it seems that System.getenv() was introduced in 1.5?
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n", envName, env.get(envName));
}
System.getenv() will return a Map<String,String> with all of the environment variables.
But you could just as easily switch to ProcessBuilder which is a more convenient API to start new processes.
With ProcessBuilder you can simply call environment() and get a Map that contains existing environment variables and which you can manipulate how you want: i.e., if you add something to it, then that will be added to the new processes environment variables. If you remove something from it, it will not be present in the new process.
If you run an external shell, you can use it to set environment variables. e.g.
bash -c ENV1=hi ENV2=bye echo $ENV1 $ENV2
This only works if you have a UNIX shell (or cygwin)
You should migrate away from Java 1.4 and Java 5.0. Even Java 6 you might consider upgrading to Java 7.
Related
My OS is windows7. I want to read the environment variables in my Java application. I have searched google and many people's answer is to use the method System.getProperty(String name) or System.getenv(String name). But it doesn't seem to work. Through the method, I can read some variable's value that defined in the JVM.
If I set an environment variable named "Config", with value "some config information", how can I get the value in Java?
You should use System.getenv(), for example:
import java.util.Map;
public class EnvMap {
public static void main (String[] args) {
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
}
}
When running from an IDE you can define additional environment variable which will be passed to your Java application. For example in IntelliJ IDEA you can add environment variables in the "Environment variables" field of the run configuration.
Notice (as mentioned in the comment by #vikingsteve) that the JVM, like any other Windows executable, system-level changes to the environment variables are only propagated to the process when it is restarted.
For more information take a look at the "Environment Variables" section of the Java tutorial.
System.getProperty(String name) is intended for getting Java system properties which are not environment variables.
In case anyone is coming here and wondering how to get a specific environment variable without looping through all of your system variables you can use getenv(String name). It returns "the string value of the variable, or null if the variable is not defined in the system environment".
String myEnv = System.getenv("env_name");
I would like to run a parallel Java threaded program and take advantage of multiprocessor execution.
However I need to set the environment variable, to enable a multi-threaded environment. I understand that you can set the environment by issuing setenv PARALLEL 4 OR setenv OMP_NUM_THREADS 4 (for an OpenMP program).
This should enable 4 processors to run concurrently if you have 4 processor.
My Question is:
where do you issue the above command (SETENV) and how do you do it?
In java you can call System.getenv("NUM_THREADS") to get the NUM_THREADS. However there is no clear way of setting the environment. I am running AMD-x64 machine: OS: Windows 8, Processor: AMD E-300 APU Dual-Core processor, Ram: 4.00GB, System Type: 64-bit OS.
Below is the link which explains on how to set environment variable in a Windows machine manually:
http://www3.ntu.edu.sg/home/ehchua/programming/howto/Environment_Variables.html
A piece taken from above link (must read the link completely, its very rich in knowledge):
Display Variables and their Values
To list all the variables and their values, start a CMD shell (Click "Start" button ⇒ Run ⇒ Enter "cmd") and issue the command "set". To display a particular variable, use command "set varname". For examples,
// Display all the variables (in NAME=VALUE pairs)
prompt> set
COMPUTERNAME=xxxxxxx
OS=xxxxxxx
PATH=xxxxxxx
.......
// Display a particular variable
prompt> set COMPUTERNAME
COMPUTERNAME=xxxxxx
// OR use echo command with variable enclosed within a pair of '%'s
prompt> echo %COMPUTERNAME%
COMPUTERNAME=xxxxxx
Try issuing a set command on your system, and study the environment variables listed. Pay particular attention to the variable called PATH.
Set/Change/Unset a Variable
To set (or change) a variable, use command "set varname=value". There shall be no spaces before and after the '=' sign. To unset an environment variable, use "set varname=", i.e., set it to an empty string.
prompt> set varname
prompt> set varname=value
prompt> set varname=
prompt> set
Display the value of the variable
Set or change the value of the variable (Note: no space before and after '=')
Delete the variable by setting to empty string (Note: nothing after '=')
Display ALL the environment variables. For examples,
// Set an environment variable
prompt> set MY_VAR=hello
// Display
prompt> set MY_VAR
MY_VAR=hello
// Unset an environment variable
prompt> set MY_VAR=
// Display
prompt> set MY_VAR
Environment variable MY_VAR not defined
A variable set via the "set" command under CMD is a local variable, available to the current CMD session only.
If you want to set the same using Java code, below is one example:
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("CMD", "/C", "SET");
Map<String, String> env = pb.environment();
env.put("MYVAR", "myValue");
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
char[] buf = new char[1024];
while (!isr.ready()) {
;
}
while (isr.read(buf) != -1) {
System.out.println(buf);
}
}
If you want to pass some value to your program, you could also do that in command line:
java -DMyVar=varValue <main program>
This value could be read as:
String myVar= System.getProperty("MyVar");
I believe setenv is a command for linux/unix.
In windows 7, you can use the setx command in command prompt to set a User Environment Variable. e.g:
setx myvariablename myvariablevalue
Or you can do it through the GUI:
Right click My Computer -> Properties -> Advanced -> Environment Variables
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I set environment variables from Java?
I'm trying to set an environment variable, and read it back to verify it was actually set.
I've got the following :
import java.io.IOException;
public class EnvironmentVariable
{
public static void main(String[] args) throws IOException
{
Runtime.getRuntime().exec("cmd.exe set FOO=false");
String s = System.getenv("FOO");
System.out.println(s);
}
}
However, it appears that FOO is always null, meaning its probably not set correctly.
Do I have the exec command correct? The javadocs state it can take a string argument as the command.
Any ideas?
There are overloaded exec methods in which you can include an array of environment variables. For example exec(String command, String[] envp).
Here's an example (with proof) of setting an env variable in a child process you exec:
public static void main(String[] args) throws IOException {
String[] command = { "cmd", "/C", "echo FOO: %FOO%" };
String[] envp = { "FOO=false" };
Process p = Runtime.getRuntime().exec(command, envp);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = reader.readLine();
System.err.println(s);
}
However, that sets the variable in the env of the created process, not of your current (Java) process.
Similarly, if you are creating a process from Ant (as you mention in comments to aix) using the exec task, then you can pass environment variables to the child process using nested env elements, e.g.
<exec executable="whatever">
<env key="FOO" value="false"/>
</exec>
This won't work. When you start a new process, that process receives a copy of the environment. Any changes it then makes to environment variables are made within that copy, and at no point will become visible to the caller.
What are you actually trying to achieve?
By running "cmd.exe", you start a new process, which receives the new environment variable, however the java process does not get that new environment variable set this way.
In Unix/Windows, each process has it's own set of environment variables and inherits the environment variables from it's parent during process creation.
System.getenv() only returns the environment variables that were set when the process was started, as far as I see there is no way to change the environment variables of the java process itself.
The only way you can check if the set works is by starting a small batch script where you set and do the check in one process.
It's null because you launch another cmd.exe: it's a different environment from the one of your Java application (cf aix answer).
I don't think the Java runtime can change an environment variable: it can read them, but can't change them.
If you want to change a system property available in your executing JVM, use System.setProperty(String key, String value).
I have an application which uses DirectByteBuffers to store data, but I'd like to know what MaxDirectMemorySize is so I don't accidentally exceed it.
Without configuring this manually, how can I figure out, from within the program, what MaxDirectMemorySize is?
The accepted answer only works if the option is explicitly specified on the command line. As of Java 6, you can access the option directly using the HotSpotDiagnosticMXBean. The following Java 7 code can read it conveniently:
final HotSpotDiagnosticMXBean hsdiag = ManagementFactory
.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
if (hsdiag != null) {
System.out.println(hsdiag.getVMOption("MaxDirectMemorySize"));
}
Note that this may return a value of zero, meaning to use the default setting, which is equal to Runtime.getRuntime().maxMemory(). For example, with Oracle JDK 7u71 64-bit on Windows 7, this returns 3,690,987,520.
Alternatively, if you're willing to resort to accessing the sun.misc package, it's available directly by calling sun.misc.VM.maxDirectMemory().
Yuu can get ALL JVM parameters with...
RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
List<String> args=RuntimemxBean.getInputArguments();
for(int i=0;i<args.size();i++) {
System.out.println(args.get(i));
}
What is the best/foolproof way to get the values of environment variables in Windows when using J2SE 1.4 ?
You can use getEnv() to get environment variables:
String variable = System.getenv("WINDIR");
System.out.println(variable);
I believe the getEnv() function was deprecated at some point but then "undeprecated" later in java 1.5
ETA:
I see the question now refers specifically to java 1.4, so this wouldn't work for you (or at least you might end up with a deprecation warning). I'll leave the answer here though in case someone else stumbles across this question and is using a later version.
There's a switch to the JVM for this. From here:
Start the JVM with the "-D" switch to pass properties to the application
and read them with the System.getProperty() method.
SET myvar=Hello world
SET myothervar=nothing
java -Dmyvar="%myvar%" -Dmyothervar="%myothervar%" myClass
then in myClass
String myvar = System.getProperty("myvar");
String myothervar = System.getProperty("myothervar");
You have definitely no way to access environment variables straigthly from java API. The only way to achieve that with Runtime.exec with such a code :
Process p = null;
Runtime r = Runtime.getRuntime();
String OS = System.getProperty("os.name").toLowerCase();
// System.out.println(OS);
if (OS.indexOf("windows 9") > -1) {
p = r.exec( "command.com /c set" );
}
else if ( (OS.indexOf("nt") > -1)
|| (OS.indexOf("windows 2000") > -1 )
|| (OS.indexOf("windows xp") > -1) ) {
// thanks to JuanFran for the xp fix!
p = r.exec( "cmd.exe /c set" );
}
Although you can access Java variables thanks to System.getProperties();
But you would only get some env variables mapped by JVM itself, and additional data you could provide on java command line with "-Dkey=value"
For more information see http://www.rgagnon.com/javadetails/java-0150.html
Pass them into the JVM as -D system properties, for example:
java -D<java var>=%<environment var>%
That way you don't become tied to a particular OS.
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n", envName, env.get(envName));
}
Apache Commons Exec provides with "org.apache.commons.exec.environment.EnvironmentUtils" a way to get the environment variables on JDK's prior 1.5:
(String) EnvironmentUtils.getProcEnvironment().get("SOME_ENV_VAR")