Java POI - 错误:无法读取整个标头

时间:2013-06-17 09:49:42

标签: java apache-poi

我正在尝试通过POI库读取带有java的.doc文件。这是我的代码:

FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
WordExtractor extractor = new WordExtractor(document);
String [] fileData = extractor.getParagraphText();

我有这个例外:

java.io.IOException: Unable to read entire header; 162 bytes read; expected 512 bytes
at org.apache.poi.poifs.storage.HeaderBlock.alertShortRead(HeaderBlock.java:226)
at org.apache.poi.poifs.storage.HeaderBlock.readFirst512(HeaderBlock.java:207)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:138)
at MicrosoftWordParser.getDocString(MicrosoftWordParser.java:277)
at MicrosoftWordParser.main(MicrosoftWordParser.java:86)

我的文件没有损坏,我可以使用Microsoft Word启动它。

我正在使用poi 3.9(最新稳定版)。

你有解决问题的想法吗?

谢谢。

5 个答案:

答案 0 :(得分:2)

readFirst512()将读取Inputstream的前512个字节,如果没有足够的字节可读则抛出异常。我认为您的文件不够大,无法被POI阅读。

答案 1 :(得分:0)

这可能不是一个正确的Word文件。真的只有162个字节吗?检查你的文件系统。

我建议使用Word或LibreOffice创建一个新的Word文件,然后尝试使用您的程序阅读它。

答案 2 :(得分:0)

你应该试试这个程序。 package file_opration;

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile {
public static void main(String[] args) {
File file = null;
WordExtractor extractor = null ;
try {

   file = new File("filepath location");
   FileInputStream fis=new FileInputStream(file.getAbsolutePath());
   HWPFDocument document=new HWPFDocument(fis);
   extractor = new WordExtractor(document);
   String [] fileData = extractor.getParagraphText();
   for(int i=0;i<fileData.length;i++){
     if(fileData[i] != null)
       System.out.println(fileData[i]);
   }
}
catch(Exception exep){}
  }
}

答案 3 :(得分:0)

啊,你有一个文件,然后你花了大量内存通过将文件隐藏在InputStream后面将整个内容缓冲到内存中......不要!如果您有文件,请将其提供给POI。只有POI是一个InputStream,如果这就是你的全部

您的代码应该是:

 NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("myfile.doc"));
 HWPFDocument document = new HWPFDocument(fs.getRoot());

这会更快并且使用更少的内存将其读入InputStream,如果文件出现问题,通常也应该获得稍微有用的错误消息

答案 4 :(得分:0)

一个162字节的MS Word .doc可能是&#34;所有者文件&#34;。

表示Word用于表示文件的临时文件。

他们有.doc文件扩展名,但他们不是MS Word文档。