在学习poi时经常要使用到获取模板,也经常会出现系统找不到文件的错误;
public static void main(String[] args) throws Exception {
//我们先获取模板文件;
File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
log.info(rootPath.toString());
File template = new File(rootPath, "/static/word_template/test.docx");
log.info(template.toString());
FileInputStream inputStream = new FileInputStream(template);
XWPFDocument document = new XWPFDocument(inputStream);
}
D:\develop\IdeaProjects\poi_test\target\classes\static\word_template\test.docx
当上述代码在java/主代码目录下它找的是编译后的classes包下的模板文件,我们平常将模板放在resouce包下,这样是可以找的到的,但是当我们使用测试代码时,由于测试代码是在test包下,他寻找的是编译后的test_classes这个包,这个包下面是没有模板文件的,就会发生错误,此外在出现该错误时即使在java包下的正常代码也会出现,可能时在加入编译时没有正常编译导致的,此时删除target包进行重新编译即可;
public void testA() throws Exception {
//我们先获取模板文件;
File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
log.info(rootPath.toString());
File template = new File(rootPath, "/static/word_template/test.docx");
log.info(template.toString());
FileInputStream inputStream = new FileInputStream(template);
XWPFDocument document = new XWPFDocument(inputStream);
java.io.FileNotFoundException: D:\develop\IdeaProjects\poi_test\target\test-classes\static\word_template\test.docx (系统找不到指定的路径。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at com.heima.PoiTestApplicationTests.testA(PoiTestApplicationTests.java:25)
at su