下面是一个示例,取自旨在通过 GhostScript 将 EPS 转换为 PDF 的代码:
// Start the script as OS process.
ProcessBuilder pb = new ProcessBuilder(gsExecutable, pdfFileName, epsFile.getName());
pb.directory(gsDir);
pb.redirectErrorStream(true);
Process proc = pb.start();
final InputStream stdErrInStream = proc.getErrorStream();
final InputStream stdOutInStream = proc.getInputStream();
// Read the STDERR-Stream.
String className = EpsToJpegConverter.class.getName();
final ByteArrayOutputStream stdErrOutStream = new ByteArrayOutputStream();
new Thread(new Runnable() {
@Override
public void run() {
try {
byte[] buf = new byte[16];
int len = -1;
while ((len = stdErrInStream.read(buf)) != -1) {
stdErrOutStream.write(buf, 0, len);
}
stdErrFertig = true;
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
}
}, className + " Script STDERR Reader").start();
// Read the STDOUT-Stream.
final ByteArrayOutputStream stdOutOutStream = new ByteArrayOutputStream();
new Thread(new Runnable() {
@Override
public void run() {
try {
byte[] buf = new byte[4096];
int len = -1;
while ((len = stdOutInStream.read(buf)) != -1) {
stdOutOutStream.write(buf, 0, len);
}
stdOutFertig = true;
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
}
}, className + " Script STDOUT Reader").start();
// Wait for the process to finish.
int waitFor = proc.waitFor();
if (waitFor != 0) {
// If an error occured, the return code is != 0.
// In this case wait for the reading threads to finish.
while (!stdOutFertig || !stdErrFertig) {
Thread.sleep(100);
}
throw new EpsConverterException("Das Konvertierungsscript " + gsExecutable
+ " wurde nicht erfolgreich ausgeführt.\nStandardausgabe:\n" + new String(stdOutOutStream.toByteArray())
+ "\nFehlerausgabe:\n" + new String(stdErrOutStream.toByteArray()));
}
HTH。
编辑:也许读取转换后的图像字节的代码也很有趣:
// If everything worked out ok, read the PDF.
pdfFile = new File(gsDir, pdfFileName);
FileInputStream pdfInStream = new FileInputStream(pdfFile);
int len = -1;
byte[] buf = new byte[4096];
ByteArrayOutputStream pdfBAOS = new ByteArrayOutputStream(65535);
while ((len = pdfInStream.read(buf)) != -1) {
pdfBAOS.write(buf, 0, len);
}
pdfInStream.close();
byte[] res = pdfBAOS.toByteArray();
return res;