Execute non-Java instructions from Java

Classes and methods to use

java.lang.Runtime#exec

The handling of the result is carried out using the returned java.lang.Process.

Code example

Process proc = Runtime.getRuntime().exec( "java --version" );

Execution example

jshell> Process proc = Runtime.getRuntime().exec( "java --version" );
proc ==> Process[pid=19916, exitValue="not exited"]

jshell> proc.exitValue();
$2 ==> 0

Input / output

Note that the method name is the viewpoint from the side that executed Process # exec **.

Output from the execution process

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!!
* It is assumed that NotExist.java does not exist.

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

Input to the execution process


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

Other

--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

Execute non-Java instructions from Java
Execute Java code from cpp with cocos2dx
Call Java from JRuby
Changes from Java 8 to Java 11
Sum from Java_1 to 100
Eval Java source from Java
Access API.AI from Java
From Java to Ruby !!
Migration from Cobol to JAVA
Java starting from beginner, override
Creating ElasticSearch index from Java
New features from Java7 to Java8
Connect from Java to PostgreSQL
Java starting from beginner, inheritance
Java life starting from scratch
Using Docker from Java Gradle
From Ineffective Java to Effective Java
JavaScript as seen from Java
Call Kotlin's sealed class from Java
Java, abstract classes starting from beginners
Code Java from Emacs with Eclim
Get country from IP address (Java)
Run a batch file from Java
[Java] Remove whitespace from character strings
Akka hands-on preparation procedure from Java
Access Teradata from a Java application
Use Chrome Headless from Selenium / Java
Execute packaged Java code with commands
Java to be involved from today
From Java to VB.NET-Writing Contrast Memo-
Java overload constructor starting from beginner
Java, interface to start from beginner
[Oracle] Execute Windows batch from trigger
The road from JavaScript to Java
Reintroducing Java 8 available from Android Studio 2.4
Call TensorFlow Java API from Scala
[Java] Conversion from array to List
Sample code using Minio from Java