请往下滑到第2个更新。我不想改变这个问题的先前上下文。
我正在从Java应用程序中使用wkhtmltoimage。
标准使用方法是 - path-to-exe http://url.com/ image.png
。
根据他们的文档,如果我们用-
代替输入URL,则输入会转换为STDIN。
我正在使用ProcessBuilder
启动进程 -
ProcessBuilder pb = new ProcessBuilder(exe_path, " - ", image_save_path);
Process process = pb.start();
现在我无法找出如何将输入流导入到这个进程中。
我已经读取了一个模板文件到一个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>";
我该如何将内容
导入到进程的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.
的错误。还需要做什么来保持管道的开放状态?
getOutputStream
这个名字对于实际用途来说非常不明确:返回连接到子进程正常输入的输出流。向该流输出的内容将被管道传输到由此Process对象表示的进程的标准输入中。 在Python中,它只是被称为stdin
,但是有人可能会认为写入名为stdin
的东西在语义上不正确。 - Mmmh mmh