我正在尝试使用 Java 将 pdf 转换为 txt。我已经尝试过 Apache PDFBox,但由于某些奇怪的原因,它不会转换整个文档。出于这个原因,我决定通过执行 Runtime.getRuntime().exec() 调用来使用 pdftotext。问题是,虽然在我的终端上 pdftotext 工作完美,但 exec() 调用给我错误代码 1(有时甚至是 99)。 这是调用:
pdftotext "/home/www-data/CANEFS_TEST/Hello/ciao.pdf" "/tmp/ciao.pdf.txt"
这是代码
private static File callPDF2Text(File input,File output){
assert input.exists();
assert Utils.getExtension(input).equalsIgnoreCase("pdf");
assert Utils.getExtension(output).equalsIgnoreCase("txt") : output.getAbsoluteFile().toString();
Process p=null;
try {
System.out.println(String.format(
PDF2TXT_COMMAND,
input.getAbsolutePath(),
output.getAbsolutePath()));
p=Runtime.getRuntime().exec(String.format(
PDF2TXT_COMMAND,
input.getAbsolutePath(),
output.getAbsolutePath()));
p.waitFor();
if (p.exitValue()!=0){
throw new RuntimeException("exit value for pdftotext is "+p.exitValue());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return output;
}
这是 PDF2TXT_COMMAND 字符串定义:
public static final String PDFTXT_COMMAND="pdftotext \"%s\" \"%s\"";
我知道通常这些类型的错误是由权限设置引起的。因此,这是 Hello 文件夹中 ls -l 命令的输出:
ls -l /home/www-data/CANEFS_TEST/Hello/
total 136
-rwxrwxr-- 1 www-data www-data 136041 mar 27 16:31 ciao.pdf
另外,请注意创建进程的用户是 koldar,它在组 www-data 本身中。 感谢您的时间和耐心等待!
最佳答案
不要在格式字符串中使用 "...这些字符由 shell 专门解析,您不使用 shell 来启动命令...
我可以建议你使用 exec(String [])
而不是 exec(String)
这样你就可以分开你命令的参数:
String []command = new String[3];
command[0] = "pdftotext";
command[1] = input.getAbsolutePath();
command[2] = output.getAbsolutePath();
Runtime.getRuntime().exec(command);
那应该行得通。如果不是,那可能是 dir 的访问权限问题。
关于java - 命令从 exec() 失败但在终端上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29556314/