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

1
  • 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). Also you can store a full path to the license in the registry but it depends on your environment. Commented Jun 17, 2012 at 18:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 Yes, it will work, but I think he has to understand what was happened :)
He's already using Eclipse to mask his lack of knowledge with CLASSPATH. I think that ship has already sailed.
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`
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.