java.lang.Runtime#exec
The handling of the result is carried out using the returned java.lang.Process.
Process proc = Runtime.getRuntime().exec( "java --version" );
jshell> Process proc = Runtime.getRuntime().exec( "java --version" );
proc ==> Process[pid=19916, exitValue="not exited"]
jshell> proc.exitValue();
$2 ==> 0
Note that the method name is the viewpoint from the side that executed Process # exec **.
import java.io.*;
Process proc = Runtime.getRuntime().exec( "java Hello" );
String line = null;
try ( var buf = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ) ) {
while( ( line = buf.readLine() ) != null ) System.out.println( line );
}
# Hello.Java contents
public class Hello {
public static void main( String[] args ) {
System.out.println( "Hello, world!!" );
}
}
Result
Hello, world!!
import java.io.*;
Process proc = Runtime.getRuntime().exec( "javac NotExist.java" );
String line = null;
try ( var buf = new BufferedReader( new InputStreamReader( proc.getErrorStream() ) ) ) {
while( ( line = buf.readLine() ) != null ) System.out.println( line );
}
Result
error:File not found: NotExist.java
how to use: javac <options> <source files>
For a list of available options--Use help
import java.io.*;
Process proc = Runtime.getRuntime().exec( "java -cp . SampleCode" );
try ( var buf = new BufferedWriter( new OutputStreamWriter( proc.getOutputStream() ) ) ) {
buf.write( "3" );
buf.newLine();
buf.write( "5" );
buf.newLine();
}
//Display the output contents from the acquired process
try ( var buf = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ) ) {
while( ( line = buf.readLine() ) != null ) System.out.println( line );
}
// SampleCode.Java contents
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SampleCode {
public static void main( String[] args ) throws Exception{
try ( var buf = new BufferedReader(
new InputStreamReader( System.in )
) ) {
int x = Integer.parseInt( buf.readLine() );
int y = Integer.parseInt( buf.readLine() );
System.out.println( x + "*" + y + "=" + x*y );
}
}
}
Result
3*5=15
--Execute Process # waitFor to wait for the process to complete.
--The exit code of the process can be obtained with Process # exitValue.
However, if you call exitValue when the process is not terminated, an exception (java.lang.IllegalThreadStateException) will occur. (See below)
Exception in thread "main" java.lang.IllegalThreadStateException: process has not exited
at java.base/java.lang.ProcessImpl.exitValue(ProcessImpl.java:478)
Recommended Posts