Maroun
Maroun

Reputation: 95968

Running echo command from Java

I want to print the output of echo %path% from Java instead of cmd.

I have the following code:

private void getPath() throws IOException {
    String getPath = "cmd.exe /C echo %path%";
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(getPath);
    BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String commandOutput = "";
    while (commandOutput != null) {
        commandOutput = reader.readLine();
        System.out.println(commandOutput);
    }
}

If I run echo %path% from the cmd the output begins with:

C:\Oracle\Ora11\bin;C:\Oracle\Ora10\bin;C:\Program Files\Common

But the output of the Java program begins with:

C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386

and only after this line, the rest of the output is similar.

Why is this happening?

Upvotes: 2

Views: 14350

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

You are probably running your test from IDE (eg Eclipse). Try the same from command line. BTW there is another way to print environnment variables from Java

System.out.println(System.getenv("PATH"));

Upvotes: 1

Andremoniy
Andremoniy

Reputation: 34900

Looks like Java appends to %path% its own paths. Nothing else.

Upvotes: 3

Related Questions