0

I have created a java project in eclipse and added certain text files like follows

FileReader fin=null;
BufferedReader bin=null;
fin=new FileReader("src/main/resources/League.txt");
bin=new BufferedReader(fin);

But after creation of the ruunable jar or just simple jar when I run the jar file it is showing that no text file is found or the path is not found. But I have added the text files in the main.resource of my project. How to handle it?

Pritam
  • 31
  • 8

3 Answers3

0

Make sure there's a file in the latest Java version directory src\main\resources\League.txt. For example, say for Windows, C:\Program Files\Java\jdk1.7.0_25\src\main\resources\League.txt. You need to give front slashes, not back ones. Also, this should be the code:

FileReader fin=null;
BufferedReader bin=null;
fin=new FileReader("src\\main\\resources\\League.txt"); // Because of Unicode restrictions. 
bin=new BufferedReader(fin);

Maybe you check this as well: How to get a path to a resource in a Java JAR file

Community
  • 1
  • 1
Mission Coding
  • 301
  • 4
  • 12
  • but I have to create a jar file of my project that would be path independant. So what should be the wayout? – Pritam Apr 29 '14 at 14:49
  • Jar files break hard-coded paths; generally you'll have to use `____.class.getClassLoader().getResource()` or `_____.class.getResource()` along with some path relative to the location of _____ to retrieve the text file. (don't know if the syntax is correct on those, but I think it's fairly close to those) – awksp Apr 29 '14 at 14:50
0

Use URLClassLoader.getSystemResourceAsStream, this works in jars and in eclipse...

danibuiza
  • 77
  • 1
  • 7
0

Try this. Even though the file is in src/resources you need not say src folder in path.

BufferedReader br = null;

try {

    String sCurrentLine;

    URL url = ClassLoader.getSystemResource("resources/League.txt");
    br = new BufferedReader(new InputStreamReader(url.openStream()));

    while ((sCurrentLine = br.readLine()) != null) {
        System.out.println(sCurrentLine);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (br != null)br.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
Syam S
  • 8,421
  • 1
  • 26
  • 36