Search code examples
javaembedded-resource

how to access resources(Excel file) in jar file


Hi i have exported my java project as executable jar file. inside my project I am accessing a Excel file containing some data. Now I am not able to access the Excel file when I am trying to access the file.

My project structure is:
Java_Project_Folder
- src_Folder
- resources_Folder(Containing excel file)

I am accessing the excel file like

FileInputStream file=new FileInputStream(new File(System.getProperty("user.dir")
+File.separator+"resources"+File.separator+"Excel.xlsx"));

I have tried accessing this file using getResourceAsStream like:

FileInputStream file=(FileInputStream) this.getClass().getResourceAsStream
("/resources/Excel.xlsx");

But i am getting in is null exception. whats wrong can anyone help?


Solution

  • I tried this and it is working for me.

    My Test1 class is in default package, just check where your accessing class is in any package, if it is then go back to exact resource folder from classpath like this "../"

    public class Test1 {
    
        public static void main(String[] args) {
            new Test1();  
        }
        Test1(){
            BufferedInputStream file= (BufferedInputStream) this.getClass().getResourceAsStream("resources/a.txt");
            try {
                System.out.println((char)file.read());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }