How to pipe InputStream to ProcessBuilder

后端 未结 5 2055
傲寒
傲寒 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:07

    Is there a reason you are using DataInputStream to read a simple text file? From the Java documentation

    A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way

    It's possible that the way you are reading the file causes an EOF to be sent to the outputstream causing the pipe to end before it gets to your string.

    You requirements seems to be to read the file simply to append to it before passing it on to the wkhtmltoimage process.

    You're also missing a statement to close the outputstream to the process. This will cause the process to wait (hang) until it gets an EOF from the input stream, which would be never.

    I'd recommend using a BufferedReader instead, and writing it directly to the outputstream before appending your additional string. Then call close() to close the stream.

    ProcessBuilder pb = new ProcessBuilder(full_path, " - ", image_save_path);
    pb.redirectErrorStream(true);
    
    Process process = null;
    try {
        process = pb.start();
    } catch (IOException e) {
        System.out.println("Couldn't start the process.");
        e.printStackTrace();
    }
    
    System.out.println("reading");
    
    try {
        if (process != null) {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    
            BufferedReader inputFile = new BufferedReader(new InputStreamReader(new FileInputStream(currentDirectory+"\\bin\\template.txt")));
    
            String currInputLine = null;
            while((currInputLine = inputFile.readLine()) != null) {
                bw.write(currInputLine);
                bw.newLine();
            }
            bw.write("
    Loading chart...
    "); bw.newLine(); bw.close(); } } catch (IOException e) { System.out.println("Either couldn't read from the template file or couldn't write to the OutputStream."); e.printStackTrace(); } BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String currLine = null; try { while((currLine = br.readLine()) != null) { System.out.println(currLine); } } catch (IOException e) { System.out.println("Couldn't read the output."); e.printStackTrace(); }

提交回复
热议问题