I am trying to read a file in Java. I wrote a program and saved the file in the exact same folder as my program. Yet, I keep getting a FileNotFoundException. Here is the code:
public static void main(String[] args) throws IOException {
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
File f = new File("file.txt");
ArrayList<String> al = readFile(f, ht);
}
public static ArrayList<String> readFile(File f, Hashtable<String, Integer> ht) throws IOException{
ArrayList<String> al = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
int ctr = 0;
}
...
return al;
}
Here is the stack trace:
Exception in thread "main" java.io.FileNotFoundException: file.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at csfhomework3.ScramAssembler.readFile(ScramAssembler.java:26)
at csfhomework3.ScramAssembler.main(ScramAssembler.java:17)
I don't understand how the file can't be found if it's in the exact same folder as the program. I'm running the program in eclipse and I checked my run configurations for any stray arguments and there are none. Does anyone see what's wrong?
Because the File
isn't where you think it is. Print the path that your program is attempting to read.
File f = new File("file.txt");
try {
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
Per the File.getCanonicalPath()
javadoc, A canonical pathname is both absolute and unique. The precise definition of canonical form is system-dependent.
Check the Eclipse run configuration. Look on the second tab "Arguments", at the bottom pane where it says "Working Directory". That's the place where the program gets launched and where it will expect to find the file. Usually in Eclipse it launches your program with the current working directory set to be the base project directory. If you have the java class file in a source folder and are using proper package (e.g., "com.mycompany.package"), then the data file will be in a directory like "src/com/mycompany/package" which is quite a different directory from the project directory.
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With