Faz006
Faz006

Reputation: 73

How to add resources into jar file

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

Upvotes: 4

Views: 6363

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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") );
     //...

Upvotes: 2

Mihai Toader
Mihai Toader

Reputation: 12243

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>

Upvotes: 1

Related Questions