0

I have an app, that needs to read files line by line. I'm using the following code and it's ok.

public ArrayList <String[]> LoadServersFile(String filename){
BufferedReader br=null;
ArrayList <String> result = new ArrayList();
try {
    String sCurrentLine;
    InputStreamReader reader =  new InputStreamReader(this.getClass().getResourceAsStream("/"+filename));
    br = new BufferedReader(new FileReader(filename));

    while ((sCurrentLine = br.readLine()) != null) {
        result.add(sCurrentLine);
    }
    br.close();
} catch (FileNotFoundException ex) {
    Logger.getLogger(FilesIO.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
    Logger.getLogger(FilesIO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;

}

But after compiling project and launching it, br.readLine() is always null. Setting "/file.txt" and putting this file to C:/ disk fixes the bug, but i need this file to be in folder with my .jar file

crzbt
  • 183
  • 4
  • 14

1 Answers1

3

You can get your file using the getResourceAsStream method:

InputStreamReader reader =  new InputStreamReader(this.getClass().getResourceAsStream("/file.txt"));
BufferedReader br = new BufferedReader(reader);   
TheEwook
  • 11,037
  • 6
  • 36
  • 55