问题
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
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:
回答1:
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.
回答2:
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
.
来源:https://stackoverflow.com/questions/11073702/java-file-relative-path-in-eclipse