Reputation: 49
So I'm trying to read in from a config file in my Eclipse project, but it can't locate the file. Here's my code.
public void readConfigFile () {
//URL url = Test.class.getClassLoader().getResource("myfile.txt");
//System.out.println(url.getPath());
URL url = getClass().getResource("/config");
System.out.println(url);
try {
BufferedReader read = new BufferedReader(new FileReader(url.toString()));
//read in values for constants from config file
System.out.println(BASE_URL);
BASE_URL = read.readLine().split("\t")[1];
System.out.println(BASE_URL);
read.close();
}
catch (Exception e)
{
System.out.println("Read from config file failed. Terminating program");
System.out.println(e);
System.exit(1);
}
}
When I run, it prints the url
variable as:
/Users/myname/Development/workspace/New_API/bin/config
But it fails to find the file when running the BufferedReader command. I get:
Read from config file failed. Terminating program
java.io.FileNotFoundException:
file:/Users/myname/Development/workspace/New_API/bin/config.txt (No such file or directory)
When I go to the bin directory of my code however, the config file is there. In the root bin directory, following the exact path given by the URL. What is messing Eclipse up?
Upvotes: 0
Views: 2185
Reputation: 280172
When getting a resource from the class loader, you're getting it from the classpath, not from the file system. If your application was packaged as a jar, you wouldn't have access to the resource through the File
or FileInputStream
APIs since the resource is part of the archive. Instead, you can access the input stream of the resource like so:
URL url = getClass().getResource("/config");
BufferedReader read = new BufferedReader(new InputStreamReader(url.openStream()));
// more...
Upvotes: 1