0

I am making a runnable jar file for my project.

Code

public class StandingsCreationHelper
{
    private static final String TEMPLATE_FILENAME = "Standings_Template.xls";

public static void createStandingsFile() throws Exception
{
    StandingsCreationHelper sch = new StandingsCreationHelper();

    // Get the file from the resources folder
    File templateFile = new File("TemporaryPlaceHolderExcelFile.xls");
    OutputStream outputStream = new FileOutputStream(templateFile);
    IOUtils.copy(sch.getFile(TEMPLATE_FILENAME), outputStream);
    outputStream.close();
}
}

public InputStream getFile(String fileName)
{
    return this.getClass().getClassLoader().getResourceAsStream(fileName);
}

public static void main(String[] args) throws Exception
{
    createStandingsFile();
}

Project's structure

enter image description here

Question

When I package my code in the runnable jar, my program will execute without any problems. However, if I call the main method from my IDE (Eclipse), I get the following error message, as if the resource cannot be found:

Exception in thread "main" java.lang.NullPointerException at org.apache.poi.util.IOUtils.copy(IOUtils.java:182) at standings.StandingsCreationHelper.createStandingsFile(StandingsCreationHelper.java:153) at standings.StandingsCreationHelper.main(StandingsCreationHelper.java:222)

Thanks for advance for any help!

Benoit Goderre
  • 527
  • 2
  • 9
  • 25

1 Answers1

2

You are using getClassLoader() which needs the absolute Path to the File.

Change:

public InputStream getFile(String fileName)
{
    return this.getClass().getClassLoader().getResourceAsStream(fileName);
}

to

public InputStream getFile(String fileName)
{
    return this.getClass().getResourceAsStream(fileName);
}

Now your can use the relative path, seen from your class. Don't forget to change TEMPLATE_FILENAME to "resources/Standings_Template.xls" as mentioned in the comment.

Daniel
  • 1,027
  • 1
  • 8
  • 23