【问题标题】:Is there a way to save the obtained output from a a process object's getOutPutStream() method into a file有没有办法将从进程对象的 getOutPutStream() 方法获得的输出保存到文件中
【发布时间】:2019-07-31 17:08:53
【问题描述】:

来自此链接“Writing to the OutputStream of Java Process/ProcessBuilder as pipe”并研究我没有找到一种方法来指定从 getOutputStream() 写入进程输出的路径。

BufferedReader br = new BufferedReader(new FileReader(new File("commands.txt")));
        String[] input = br.readLine().split(" ");

        String cmd =  input[0] + " " + input[1] + " " + input[3];

        System.out.println(cmd);

        Process process = Runtime.getRuntime().exec(new String[]{"bash","-c", cmd});


        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(input[3]));

        byte[] buf = new byte[1024];
        int len;

        while ( (len = in.read()) > 0) {
            // out.write();
        }

在代码中,exec 运行一个将两个文件的结果连接起来的进程,现在我想将结果保存在一个新文件中。但是我找不到方法,因为进程中的 getOutPutStream 对象只有一种方法 write 与构造函数,该构造函数将 int[] 作为参数。提前感谢您的帮助。

【问题讨论】:

    标签: java process fileoutputstream


    【解决方案1】:

    我认为您在这种情况下混淆了InputStreamOutputStream。将它们视为代码的输入/输出。据我了解,您想获取in 阅读器中的内容并将其输出到out。我不明白您为什么需要使用getOutputStreamProcess

    从Java 9开始,有一个非常简单的解决方案,即ReadertransferTo方法。实际上,您可以将 Process 初始化后的所有内容替换为以下内容:

    process.getInputStream().transferTo(new FileOutputStream(input[3]))

    【讨论】:

    • 你是对的,我输入和输出流不匹配。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2016-02-18
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多