クラス Subprocess
java.lang.Object
com.kazurayam.subprocessj.Subprocess
Subprocess object allows you to spawn new OS subprocess using java.lang.ProcessBuilder. Subprocess#run() waits for the subprocess to finish, returns a CompletedProcess object which contains the return code, STDOUT and STDIN of the executed command.
A simple example as a JUnit5 test case:
import com.kazurayam.subprocessj.Subprocess; import com.kazurayam.subprocessj.Subprocess.CompletedProcess; import org.junit.jupiter.api.Test; class SubprocessTest { @Test void test_demo() throws Exception { Subprocess subprocess = new Subprocess(); // change the current working directory for the process in which a command is executed subprocess.cwd(new File(System.getProperty("user.home"))); // execute a command in a forked process CompletedProcess cp = subprocess.run(Arrays.asList("ls", "-la", ".")); // use the return code of the executed command System.out.println(cp.returncode()); // use the STDOUT of the executed command cp.stdout().forEach(System.out::println); // use the STDERR of the executed command cp.stderr().forEach(System.out::println); } }
The following features are supported:
- returning the return code from the Subpprocess
- capturing the STDOUT from the Subprocess
- capturing the STDERR from the Subprocess
- starting a subprocess with a modified working directory
The following features are still to be considered:
- PIPE: Connecting INPUT from other process as STDIN for the Subprocess
- Starting a Subprocess with a modified Environment variables
- inheriting the I/O of the Current Process
-
ネストされたクラスの概要
ネストされたクラス修飾子とタイプクラス説明static final class
A Data Transfer Object that contains the return code, STDOUT and STDERR out of the executed subprocess.static final class
-
コンストラクタの概要
コンストラクタ -
メソッドの概要
修飾子とタイプメソッド説明Change the current working directory.environment
(String key) Run the command written as a List<String>.
-
コンストラクタの詳細
-
Subprocess
public Subprocess()
-
-
メソッドの詳細
-
environment
-
environment
-
cwd
Change the current working directory. As default, will be set as the current working directory of the caller process "."- パラメータ:
currentWorkingDirectory
- a File object, which is a directory- 戻り値:
- the Subprocess object. for functional call chaining.
-
run
public Subprocess.CompletedProcess run(List<String> command) throws IOException, InterruptedException Run the command written as a List<String>. Wait for the command to complete, then return a Subprocess.CompletedProcess instance, in which you can read: - the return code of the subprocess - the captured STDOUT of the subprocess - the captured STDERR of the subproess Referred to a Baeldung's article "Java Executor Wait for the Threads"- パラメータ:
command
- E.g Array.asList("ls", "-la", ".")- 戻り値:
- a Subprocess.CompletedProcess instance
- 例外:
IOException
- when failed to create a Thread to consume STDOUT/STDERR from the subprocessInterruptedException
- when a Thread that consumes STDOUT/STDERR from the subprocess was interrupted
-