spring-bootdocx4j

docx4j cant load file with error java.io.FileNotFoundException


in my spring boot project iam using docx4j to load a file from the target folder although the file exists when i use system.out.print("exists) it appears in the console . any solution ? here is the code

 public void testDocx4j() throws Docx4JException, FileNotFoundException {
    File file = ResourceUtils.getFile("classpath:compare.docx");
    if(file.exists()){
      System.out.println("exists !!");
    }
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file);
    MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();

  }

i was trying to load the file with docx4j


Solution

  • The following works for me:

    import java.io.IOException;
    import java.io.InputStream;
    
    import org.docx4j.openpackaging.exceptions.Docx4JException;
    import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
    import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
    import org.docx4j.utils.ResourceUtils;
    
    public class LoadAsResource {
    
        public static void main(String[] args) throws Docx4JException, IOException {
    
            InputStream is = ResourceUtils.getResource("sample-docxv2.docx");
    
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
                    .load(is);
            MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();    
            
            System.out.println(documentPart.getXML());
        }
    
    }