如何使用 Javas ProcessBuilder 进行输入重定向?

问题描述 投票:0回答:1

如何将输入重定向应用于 Javas ProcessBuilder?

例如使用Linux的cat

cat x.txt > output.txt

我的代码

// read x.txt with cat and redirect the output to output.txt
public static void main (String args []) throws Exception
{
    List <String> params = new ArrayList <String> ();
    params.add ("cat");
    params.add ("x.txt");       
    ProcessBuilder pb = new ProcessBuilder (params);
    pb.redirectOutput (new File ("output.txt"));
    Process p = pb.start ();
    p.waitFor (3, TimeUnit.SECONDS);
    System.out.println ("exit="+p.exitValue());
}

效果很好! 但如何从文件更改为输入重定向?

cat << END > output

我尝试过这个 - 但不起作用。

public static void main (String args []) throws Exception
{
    List <String> params = new ArrayList <String> ();
    params.add ("cat");
    params.add ("/dev/stdin");
    params.add ("<<";
    params.add ("END");
    
    ProcessBuilder pb = new ProcessBuilder (params);
    pb.redirectOutput (new File ("output.txt"));
    Process p = pb.start ();
    OutputStream os = p.getOutputStream ();
    os.write ("\nblabla\nEND\n".getBytes ());
    p.waitFor (3, TimeUnit.SECONDS);
    System.out.println ("exit="+p.exitValue());
}

无论我尝试什么,它都会返回 1(而不是 0 表示成功)或未完成。

java linux processbuilder io-redirection
1个回答
0
投票

命令

cat << END > output
是一个shell命令,因此您需要通过shell运行它作为

 List.of("/bin/sh", "-c", "cat << END > output")
© www.soinside.com 2019 - 2024. All rights reserved.