1

Three days i was trying to figure out how to read file using relative file path. In eclipse this compiles and works great, but when i export app. It says that it can't find the file. here is the screenshot and code i work on.

This code works, but only in eclipse, it compiles and does job perfectly. But when i export it as as runnable jar file i get an error, that it cannot locate licenca.txt

 BufferedReader in = new BufferedReader(new FileReader(new File("licenca.txt").getPath()));
        String str;
        while ((str = in.readLine()) != null) {
      taLicenca.append(str + "\n");
      
    }

here is the screenshot of my project files

files

i have tried use of scanner function, still the same result, it works in eclipse, but doesn't work on export. Here is the error message:

error

Community
  • 1
  • 1
Игор
  • 355
  • 3
  • 10
  • 24
  • Relative path depends on the application working directory. Moreover i guess you can't simply access files inside your jar. Consider using `class.getResource` method if it's inside the jar. If your file is in the same folder as the jar - you can use jar's path (see [link](http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file)). Also you can store a full path to the license in the registry but it depends on your environment. – nidu Jun 17 '12 at 18:27

2 Answers2

6

I'll bet it'll work if you put that file into the classpath.

Change your code like this:

InputStream is = this.getClass().getClassLoader().getResourceAsStream("licenca.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String str;
while ((str = in.readLine()) != null) {
    taLicenca.append(str + "\n");
}

Try it and see.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • +1 Yes, it will work, but I think he has to understand what was happened :) – Sergii Zagriichuk Jun 17 '12 at 18:27
  • He's already using Eclipse to mask his lack of knowledge with CLASSPATH. I think that ship has already sailed. – duffymo Jun 17 '12 at 18:29
  • no it wont work :P when i add `InputStream is = this.getClass().getClassLoader().getResourceAsStream("licenca.txt");` it assk me to cast it to InputStream type, and when i do that displays this error on compile Exception in thread "main"` java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from java.io.InputStream to org.omg.CORBA.portable.InputStream` – Игор Jun 17 '12 at 18:31
  • I do not think about it, if it understandable for him, he will not ask this question, just copy manually resource to start folder or get from jar, as you described. – Sergii Zagriichuk Jun 17 '12 at 18:31
0

It happens because your file is exported as part of jar file, so, for creating jar file try to use ant or maven or semething else, or manually copy your file in directory with with your jar, it calls start directory.

Sergii Zagriichuk
  • 5,389
  • 5
  • 28
  • 45