次のコードを使用してプロセスビルダーを起動しています。出力を文字列にリダイレクトする方法を知りたいです。
ProcessBuilder pb = new ProcessBuilder(System.getProperty("user.dir")+"/src/generate_list.sh", filename);
Process p = pb.start();
ByteArrayOutputStream
を使用してみましたが、うまくいかないようです。
InputStream
から読み取ります。出力をStringBuilder
に追加できます:
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
Apache Commonsを使用して IOUtils を1行で実行できます。
ProcessBuilder pb = new ProcessBuilder("pwd");
String output = IOUtils.toString(pb.start().getInputStream());
Java 8の例:
public static String runCommandForOutput(List<String> params) {
ProcessBuilder pb = new ProcessBuilder(params);
Process p;
String result = "";
try {
p = pb.start();
final BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringJoiner sj = new StringJoiner(System.getProperty("line.separator"));
reader.lines().iterator().forEachRemaining(sj::add);
result = sj.toString();
p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
使用法:
List<String> params = Arrays.asList("/bin/sh", "-c", "cat /proc/cpuinfo");
String result = runCommandForOutput(params);
私はこの正確なコードを使用し、1行または複数行の結果に適しています。エラーストリームハンドラも追加できます。
あなたはこのようなことをするかもしれません:
private static BufferedReader getOutput(Process p) {
return new BufferedReader(new InputStreamReader(p.getInputStream()));
}
private static BufferedReader getError(Process p) {
return new BufferedReader(new InputStreamReader(p.getErrorStream()));
}
...
Process p = Runtime.getRuntime().exec(commande);
BufferedReader output = getOutput(p);
BufferedReader error = getError(p);
String ligne = "";
while ((ligne = output.readLine()) != null) {
System.out.println(ligne);
}
while ((ligne = error.readLine()) != null) {
System.out.println(ligne);
}
Java 7および8の場合、これは機能するはずです。
private String getInputAsString(InputStream is)
{
try(Java.util.Scanner s = new Java.util.Scanner(is))
{
return s.useDelimiter("\\A").hasNext() ? s.next() : "";
}
}
次に、コードでこれを実行します。
String stdOut = getInputAsString(p.getInputStream());
String stdErr = getInputAsString(p.getErrorStream());
私は恥知らずにそれを盗みました: Process Builderの出力を文字列にリダイレクトする方法?
プロセスビルダー行に.inheritIO();
を追加するだけです。
IE:
ProcessBuilder pb = new ProcessBuilder(script.sh).inheritIO();
さまざまなケースを処理しようとした後(stderrとstdoutの両方を処理し、これらのいずれもブロックせず、タイムアウト後にプロセスを終了し、スラッシュ、引用符、特殊文字、スペースなどを適切にエスケープします。)Apache Commons Exechttps://commons.Apache.org/proper/commons-exec/tutorial.html これは、これらすべてのことをかなりうまく行っているようです。
Javaで外部プロセスを呼び出す必要があるすべての人に、Apache Commons Execライブラリを再発明する代わりに使用することをお勧めします。
Java 8では、String.joinおよびSystem.lineSeparator()と組み合わせることができるNice lines()ストリームがあります。
try (BufferedReader outReader = new BufferedReader(new InputStreamReader(p.getInputStream()))
{
return String.join(System.lineSeparator(), outReader.lines().collect(toList()));
\\ OR using jOOλ if you like reduced verbosity
return Seq.seq(outReader.lines()).toString(System.lineSeparator())
}
ソリューション
Process Builderの出力を文字列にリダイレクトする方法は?
ProcessBuilder pb = new ProcessBuilder(System.getProperty("user.dir")+"/src/generate_list.sh", filename);
のコメントを外し、行のコメントを外して、コメントアウトします:ProcessBuilder processBuilder = new ProcessBuilder(commands);
。機能
echo 1
を実行し、出力を文字列として返す実用的な例です。使用方法と検証
binaryCommand[0]="touch";
とbinaryCommand[1]="1";
を設定し、.jar
ファイルを再コンパイルして実行することで検証されます。制限
コード
import Java.io.BufferedReader;
import Java.io.File;
import Java.io.IOException;
import Java.io.InputStreamReader;
import Java.io.PrintWriter;
import Java.util.Arrays;
import Java.util.Map;
import Java.util.StringJoiner;
public class GenerateOutput {
/**
* This code can execute a command and print the output accompanying that command.
* compile this project into a .jar and run it with for example:
* Java -jar readOutputOfCommand.jar
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
boolean answerYes = false; // no yes answer to any command prompts is needed.
// to execute a command with spaces in it in terminal, put them in an array of Strings.
String[] binaryCommand = new String[2];
// write a command that gives a binary output:
binaryCommand[0] = "echo";
binaryCommand[1] = "1";
// pass the commands to a method that executes them
System.out.println("The output of the echo command = "+executeCommands(binaryCommand,answerYes));
}
/**
* This executes the commands in terminal.
* Additionally it sets an environment variable (not necessary for your particular solution)
* Additionally it sets a working path (not necessary for your particular solution)
* @param commandData
* @param ansYes
* @throws Exception
*/
public static String executeCommands(String[] commands,Boolean ansYes) throws Exception {
String capturedCommandOutput = null;
System.out.println("Incoming commandData = "+Arrays.deepToString(commands));
File workingDirectory = new File("/mnt/c/testfolder b/");
// create a ProcessBuilder to execute the commands in
ProcessBuilder processBuilder = new ProcessBuilder(commands);
//ProcessBuilder processBuilder = new ProcessBuilder(System.getProperty("user.dir")+"/src/generate_list.sh", "a");
// this is not necessary but can be used to set an environment variable for the command
processBuilder = setEnvironmentVariable(processBuilder);
// this is not necessary but can be used to set the working directory for the command
processBuilder.directory(workingDirectory);
// execute the actual commands
try {
Process process = processBuilder.start();
// capture the output stream of the command
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringJoiner sj = new StringJoiner(System.getProperty("line.separator"));
reader.lines().iterator().forEachRemaining(sj::add);
capturedCommandOutput = sj.toString();
System.out.println("The output of this command ="+ capturedCommandOutput);
// here you connect the output of your command to any new input, e.g. if you get prompted for `yes`
new Thread(new SyncPipe(process.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(process.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(process.getOutputStream());
//This is not necessary but can be used to answer yes to being prompted
if (ansYes) {
System.out.println("WITH YES!");
stdin.println("yes");
}
// write any other commands you want here
stdin.close();
// this lets you know whether the command execution led to an error(!=0), or not (=0).
int returnCode = process.waitFor();
System.out.println("Return code = " + returnCode);
} catch (IOException e1) {
e1.printStackTrace();
}
return capturedCommandOutput;
}
/**
* source: https://stackoverflow.com/questions/7369664/using-export-in-Java
* @param processBuilder
* @param varName
* @param varContent
* @return
*/
private static ProcessBuilder setEnvironmentVariable(ProcessBuilder processBuilder){
String varName = "variableName";
String varContent = "/mnt/c/testfolder a/";
Map<String, String> env = processBuilder.environment();
System.out.println("Setting environment variable "+varName+"="+varContent);
env.put(varName, varContent);
processBuilder.environment().put(varName, varContent);
return processBuilder;
}
}
class SyncPipe implements Runnable
{
/**
* This class pipes the output of your command to any new input you generated
* with stdin. For example, suppose you run cp /mnt/c/a.txt /mnt/b/
* but for some reason you are prompted: "do you really want to copy there yes/no?
* then you can answer yes since your input is piped to the output of your
* original command. (At least that is my practical interpretation might be wrong.)
* @param istrm
* @param ostrm
*/
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}