0

I have the following code and it works fine when it is executed directly from idea

    log.info("00");
    File file = new File(classLoader.getResource("template/legalStatistic.xlsx").getFile());
    log.info("01");
    log.info(String.valueOf(file == null));
    log.info(file.getAbsolutePath());
    Workbook workbook = null;
    try {
        workbook = WorkbookFactory.create(new FileInputStream(file));
    } catch (IOException e) {
        log.error(System.getProperty("user.dir"));
        throw new RuntimeException("There is some issues with file template/legalStatistic.xlsx", e);
    }

However when this code packed in war file and executed but the command nohup java -Dfile.encoding=UTF-8 -jar name.war, the exception appears:

INFO 14859 --- [nio-9001-exec-1] biz.Services.ExportToExcelService        : 00
INFO 14859 --- [nio-9001-exec-1] biz.Services.ExportToExcelService        : 01
INFO 14859 --- [nio-9001-exec-1] biz.Services.ExportToExcelService        : false
INFO 14859 --- [nio-9001-exec-1] biz.Services.ExportToExcelService        : /home/bizon4ik/java/pitstop/target/file:/home/bizon4ik/java/pitstop/target/PitStop-1.0.war!/WEB-INF/classes!/template/legalStatistic.xlsx
ERROR 14859 --- [nio-9001-exec-1] biz.Services.ExportToExcelService        : /home/bizon4ik/java/pitstop/target
ERROR 14859 --- [nio-9001-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: There is some issues with file template/legalStatistic.xlsx] with root cause

java.io.FileNotFoundException: file:/home/bizon4ik/java/pitstop/target/PitStop-1.0.war!/WEB-INF/classes!/template/legalStatistic.xlsx (No such file or directory)
at java.io.FileInputStream.open0(Native Method) ~[na:1.8.0_181]

where is the problem? What I did wrong?

PS WorkbookFactoryis part of Apache poi lib.

Bizon4ik
  • 2,604
  • 4
  • 20
  • 46
  • Are you trying to create a new file? – Rabbit Guy Sep 21 '18 at 19:11
  • I am trying to read the existing file and based on it create a new one. The new one will be put into HTTP response. – Bizon4ik Sep 21 '18 at 19:16
  • `classpath != filesystem` –  Sep 21 '18 at 19:17
  • The getFile method of URL does not return a valid file name. It just returns part of the URL, which will never be a valid file name if you’re running from an archive like a .jar or .war. (The URL class was part of Java 1.0, and back then, URLs usually did refer to physical files.) – VGR Sep 21 '18 at 19:36
  • @VGR you are right. The solution looks like this `WorkbookFactory.create(classLoader.getResourceAsStream("template/legalStatistic.xlsx"));` – Bizon4ik Sep 21 '18 at 19:51

0 Answers0