mustafa
mustafa

Reputation: 109

Using Process in java

I'm converting some c# code to java

System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.

This is the code that i try to convert it to java.

I dont know how to run a command and use process in java. I googled it and i found something like that :

Process process = Runtime.getRuntime().exec(command);
Integer result = process.exitValue();

In the line

process.exitValue()

it gives me java.lang.IllegalThreadStateException: process has not exited.

Upvotes: 0

Views: 740

Answers (2)

PureGero
PureGero

Reputation: 957

process.exitValue() gets the number from System.exit(number) The error is thrown since the process hasn't exited yet. From the c# code it looks like you want to get the command's output, this can be done by:

int i=0;
String result = new String();
while((i = process.getInputStream().read()) >= 0)
    result += (char)i;
System.out.println(result);

Upvotes: 0

Christian Garbin
Christian Garbin

Reputation: 2532

After exec you need to wait for the command to finish with process.waitFor().

Upvotes: 2

Related Questions