请移至第二次更新。我不想更改此问题的先前上下文。
我正在使用来自 Java 应用程序的 wkhtmltoimage。
使用它的标准方式是 - path-to-exe http://url.com/ image.png
。
根据他们的文档,如果我们编写 a-
而不是输入 URL,则输入将转移到 STDIN。
我正在使用ProcessBuilder
-
ProcessBuilder pb = new ProcessBuilder(exe_path, " - ", image_save_path);
Process process = pb.start();
现在我无法弄清楚如何将输入流通过管道传输到这个进程。
我有一个模板文件读入 a DataInputStream
,并在末尾附加了一个字符串:
DataInputStream dis = new DataInputStream (new FileInputStream (currentDirectory+"\\bin\\template.txt"));
byte[] datainBytes = new byte[dis.available()];
dis.readFully(datainBytes);
dis.close();
String content = new String(datainBytes, 0, datainBytes.length);
content+=" <body><div id='chartContainer'><small>Loading chart...</small></div></body></html>";
我如何管道content
到STDIN
进程?
更新 - -
按照 Andrzej Doyle 的回答:
我已经使用了getOutputStream()
该过程:
ProcessBuilder pb = new ProcessBuilder(full_path, " - ", image_save_path);
pb.redirectErrorStream(true);
Process process = pb.start();
System.out.println("reading");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
bw.write(content);
这样做会出现错误消息:
Exception in thread "main" java.io.IOException: The pipe has been ended
第二次更新--------
当前的代码块是这样的:
try {
ProcessBuilder pb = new ProcessBuilder(full_path, "--crop-w", width, "--crop-h", height, " - ", image_save_path);
System.out.print(full_path+ "--crop-w"+ width+ "--crop-h"+ height+" "+ currentDirectory+"temp.html "+ image_save_path + " ");
pb.redirectErrorStream(true);
Process process = pb.start();
process.waitFor();
OutputStream stdin = process.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
// content is the string that I want to write to the process.
writer.write(content);
writer.newLine();
writer.flush();
writer.close();
} catch (Exception e) {
System.out.println("Exception: " + e);
e.printStackTrace();
}
运行上面的代码给了我一个IOException: The pipe is being closed.
我还需要做什么来保持管道畅通?