0

I did search to find a solutions for this issue but I could not get proper ansewer.

My problem is I have a NetBeans project which has following folder structure.

MyProject

      Source Packages
      ---------------
                     controller 
                     .
                     .
                     .
                     .
                     databaseconfiguration
                     application
                          Application.java
                     source
                          DbConfig.txt

DbConfig.txt is in source . Application.java is in application

in Application.java I do read DbConfig.txt. as following code

String path = ClassLoader.getSystemResource("source/DbConfig.txt").getPath();

File f = new File(path);
        fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
        while (br.ready()) {
            String line = br.readLine();
            if(line.isEmpty()){
                continue;
            }
            else{
         JOptionPane.showConfirmDialog(null,line);
        }

}

this is working fine when I run in Netbeans IDE.

But after building , when I try to run this using MyProject.jar it gives null pointer exception (java -jar MyProject.jar in cmd)

Please tell me how to sort out this problem. Thanks in advance.

Narendra Jaggi
  • 1,297
  • 11
  • 33
Lasan
  • 183
  • 1
  • 4
  • 20

2 Answers2

1

As long as your file is in classpath, just use ClassLoader to return an InputStream for the resource instead of using it as a File ( you cannot read the resources from within the jar as simple Files)

InputStream in = getClass().getResourceAsStream(path); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

More information here How do I read a resource file from a Java jar file?

Community
  • 1
  • 1
ingrid.e
  • 531
  • 2
  • 11
0

In the folder, from where you are running MyProject.jar, create another folder named "source" and in "source" place the file "DbConfig.txt"

Your directory should look something like this

../SomeFolder
--------------
              MyProject.jar
              .
              .
              .
              source
                    DbConfig.txt
Gokul
  • 455
  • 6
  • 17