Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

environment variable

Status
Not open for further replies.

grindstonegirl

Technical User
Jun 12, 2003
29
0
0
US
Hi
I have an environment variable set to the location of certain files are that I need to access during my program. The ideas is so the user can set the environment variable to where ever they want to put their files. How can I access the environment variable's path in my code, so I can access these files?
 
Java does not support environment variables other than what may be included in the default system properties. So the bottom line is you can’t use them unless you want to use JNI to access them.

-pete
 
If you don't want to revert to JNI, you can use the following code. It is NOT complete (some stuff needs to be closed, ...), but it will get you started... [PS : it will do the job like it is (on W200)]. (depending on the OS, you might need to change something).
Code:
import java.io.*;

public class WinCmdExample {

  public WinCmdExample() {
  }

  private String getEnv(String var) {
    String value = null;
    Runtime run = Runtime.getRuntime();
    //String[] args = { "COMMAND.COM", "/C", "notepad" };
    //String[] args = { "notepad" };
    String command = "D:\\Test\\MyCmd.cmd"; // Or .bat
    Process p=null;
    try {
      p = run.exec(command);
      InputStream is = p.getInputStream();
      InputStreamReader ir = new InputStreamReader(is);
      BufferedReader buf = new BufferedReader(ir);
      boolean end =false;
      while (!end) {
        String s = buf.readLine();
        if (s == null)
           end = true;
        else {
          if (s.startsWith(var))
            value = s.substring(var.length());
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return value;
  }

  public static void main(String[] args) {
    WinCmdExample example = new WinCmdExample();
    System.out.println(&quot;<Path=>&quot; + example.getEnv(&quot;Path=&quot;));
  }
}
[code]
========================================
MyCmd.cmd (adapt to your need)
[code]
set path
 
Hi
ok this might sound dumb but what's JNI and how can i use it?
 
&quot;The JNI is a native programming interface. It allows Java code that runs inside a Java Virtual Machine (VM) to interoperate with applications and libraries written in other programming languages, such as C, C++, and assembly.&quot;

A site with info on jni :
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top