I was trying to write a piece of Java code to read each line from a file and add it to an Arraylist. Here is my code:
// try catch block removed for clarity.
file = new TextFileIn("names.txt");
String line = null;
while ((line = file.readLine()) != null) {
list.add(line);
}
names.txt was located in the same package folder as my code. The IDE I used was Eclipse. When I run the code however I got a FileNotFoundException. The TextFileIn class comes from http://www.javaranch.com/doc/com/javaranch/common/TextFileIn.html
How could I get the file to be found?
You’re relying on the current working directory when accessing the file. The working directory depends on how you started the application. In Eclipse it’s usually the project root folder. In commandline it’s the currently opened directory. You cannot control this from inside the Java code, so this is considered a poor practice for files which are supposed to be part of the application itself.
The file is apparently in the same package as the running code, thus it’s already in the classpath and then you could (and should) just get it straight from the classpath.
If you’re calling this in
staticcontext, then replacegetClass()byYourClassName.classwhereYourClassNameis the name of the class where this code is sitting in.See also:
getResourceAsStream()vsFileInputStream