How to pipe InputStream to ProcessBuilder

后端 未结 5 2076
傲寒
傲寒 2021-01-02 12:39

Please move down to the 2nd update. I didn\'t want to change the previous context of this question.

I\'m using wkhtmltoimage from a Java app.

<
5条回答
  •  [愿得一人]
    2021-01-02 13:16

    The following code works as well:

    import java.io.*;
    import java.util.*;
    
    public class ProcessTest {
    
        public static void main(String[] args) throws Exception {
            ProcessBuilder pb = new ProcessBuilder("/home/me/stdinecho");
            pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
            Process proc = pb.start();
    
            // Input file
            DataInputStream din = new DataInputStream((new FileInputStream("/home/me/stdinecho.cp")));
            byte[] dinBytes = new byte[din.available()];
            din.readFully(dinBytes);
            din.close();
            String content = new String(dinBytes, 0, dinBytes.length);
            content = "header\n" + content + "\nfooter";
    
            BufferedInputStream procStdout = new BufferedInputStream(proc.getInputStream());
            OutputStream stdin = proc.getOutputStream();
    
            stdin.write(content.getBytes());
            stdin.flush();
        }
    
    }
    

    Here stdinecho.cpp is the program that outputs the line entered on its prompt:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        string strOutput;
        string str;
        while(getline(cin, str)) {
            cout << str << endl;
        }
    }
    

提交回复
热议问题