2016-11-29 119 views
0

我正在为我的项目制作可运行jar文件。尝试在Eclipse中使用资源时出现NullPointerException

代码

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(); 
} 

项目的结构

enter image description here

问题

当我打包我的代码在运行的JAR,我的计划将执行没有任何问题。但是,如果我从我的IDE(Eclipse)调用主方法,我会收到以下错误消息,就好像找不到资源:

线程“main”中的异常java.lang.NullPointerException at org.apache .poi.util.IOUtils.copy(IOUtils.java:182) 在standings.StandingsCreationHelper.createStandingsFile(StandingsCreationHelper.java:153) 在standings.StandingsCreationHelper.main(StandingsCreationHelper.java:222)

感谢预先任何帮助!

+0

'“/resources/Standings_Template.xls”;'??? –

+0

谢谢你的快速回答。改为提到的字符串仍然返回空指针异常。 –

+0

什么是null,输入或输出? –

回答

2

您正在使用需要文件绝对路径的getClassLoader()

变化:

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

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

现在你可以使用相对路径,从你的类可见。不要忘记将TEMPLATE_FILENAME更改为"resources/Standings_Template.xls",如评论中所述。

+0

你走了! 1+ –

+0

谢谢你的回答!不幸的是,这些更改仍然导致NullPointerException。 –

+1

也许尝试不使用前导斜杠TEMPLATE_FILENAME =“resources/Standings_Template.xls” – Daniel

相关问题