How to add resources into jar file

浪尽此生 提交于 2019-12-20 01:13:37

问题


I need to add an exel file into my jar so it's portable. I know the answer is using getClass().getResource.... but i don't have a clue on how to go about using this code.

I have the exel file in the src folder with my class files, it works in netbeans but not when i open the jar file on another PC. i get filenotfound exception

here is the code i have used:

public class WindageLogic {

  //....
  public void GetValues() throws Exception
    {


    File exel=new File("src/Calculator/table1.xls");

     Workbook w1; //reads from file

     //reads from file
     w1 = Workbook.getWorkbook(exel);

Can someone give me the code to implement which will allow me to access this file from the jar application, I've spent all weekend looking up stuff on the internet but i don't understand how i can use these getresource techniques.

thanks alot


回答1:


If your excel file is a resource, then you can't use File to manipulate it but rather resources, and I believe that it is read-only -- are you sure that this is what you want to do? You could instead load a command line String that tells the program where to start looking for the file, or create a property file that tells where to first look.

Edit 1
If you are using JExcel then you can call Workbook.getWorkbook(java.io.InputStream is) and get your resource as a Stream via Class's getResourceAsStream(...) method.

e.g.,

  public void GetValues() throws Exception   {
     Workbook w1; //reads from file
     w1 = Workbook.getWorkbook(WindageLogic.class.
          getResourceAsStream("/Calculator/table1.xls") );
     //...



回答2:


In order for the getClass().getResource() method to work the resource should be available in the classpath of the application (either packed in one of the jar files or simply on a folder on disk that is included in the classpath).

Depending on what IDE or code building tool you are using there are multiple ways of making sure it's done.

The simplest way is to put the src folder in the run classpath java -classpath src:%CLASSPATH% <your.class.name>



来源:https://stackoverflow.com/questions/7057752/how-to-add-resources-into-jar-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!