简体   繁体   中英

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

You can get your file using the getResourceAsStream method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM