Search code examples
javafilebufferedreader

Set relative path for files to read with BufferedReader


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


Solution

  • You can get your file using the getResourceAsStream method:

    InputStreamReader reader =  new InputStreamReader(this.getClass().getResourceAsStream("/file.txt"));
    BufferedReader br = new BufferedReader(reader);