How to solve a NoSuchMethodError when using POI fo

2019-05-06 15:06发布

问题:

When I was trying to implement any code of the following

File someFile = new File("D:\\arz.doc");
InputStream inputStrm = new FileInputStream(someFile);
HWPFDocument wordDoc = new HWPFDocument(inputStrm);
System.out.println(wordDoc.getText());

or:

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("D:\\arz.doc"));
WordExtractor extractor = new WordExtractor(fs);
String wordText = extractor.getText();

, the error message always comes out as following:

Exception in thread “main” java.lang.NoSuchMethodError:            
org.apache.poi.poifs.filesystem.POIFSFileSystem.getRoot()Lorg/apache/poi/poifs/filesystem/DirectoryNode;
at org.apache.poi.hwpf.HWPFDocument.(HWPFDocument.java:186)
at DB_connect.dissertation_araalz.ParseWodDocFile.main(ParseWodDocFile.java:29)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)

Could you please help me in that problem?

回答1:

You almost certainly have two copies of POI on your classpath. One is the new, latest version which contains the feature you want to use. The other is an older version that doesn't, and it seems your system is preferring the older one...

This is a common enough problem that the POI FAQ Covers this very case. Ideally, just look at your classpath, and try to identify the extra older POI jar. However, if that doesn't work, try this snippet of code from the POI FAQ:

ClassLoader classloader =
   org.apache.poi.poifs.filesystem.POIFSFileSystem.class.getClassLoader();
URL res = classloader.getResource(
         "org/apache/poi/poifs/filesystem/POIFSFileSystem.class");
String path = res.getPath();
System.out.println("Core POI came from " + path);

That will print out the filename of the POI jar you're using, so you can work out where the older copy is coming from and remove it!



回答2:

As @Gagravarr has pointed out, try changing versions of all poi libraries to a common version. I fixed it the same way.