我正在使用 Apache Commons 在 Google App Engine 中上传一个 .docx 文件,如此链接中所述 File upload servlet .上传时,我还想使用 Apache POI 库提取文本。
如果我将其传递给 POI API:
InputStream stream = item.openStream();
我得到以下异常:
java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream
public static String docx2text(InputStream is) throws Exception {
return ExtractorFactory.createExtractor(is).getText();
}
我正在上传有效的 .docx 文档。如果我传递一个 FileInputStream 对象,POI API 工作正常。
FileInputStream fs=new FileInputStream(new File("C:\\docs\\mydoc.docx"));
最佳答案
我不知道 POI 的内部实现,但我猜他们需要一个可搜索的流。 servlet(以及一般的网络)返回的流是不可搜索的。
尝试读取全部内容,然后将其包装在 ByteArrayInputStream
中:
byte[] bytes = getBytes(item.openStream());
InputStream stream = new ByteArrayInputStream(bytes);
public static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int len;
byte[] data = new byte[100000];
while ((len = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, len);
}
buffer.flush();
return buffer.toByteArray();
}
关于java - 您的 InputStream 既不是 OLE2 流,也不是 OOXML 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23246850/