5

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?

Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59
  • 2
    The likely hood is, the file doesn't reside where you think it is. You can test this by using something like `System.out.println(new File(".").getAbsolutePath());` which will output the current working directory, this is where the file will need to reside. – MadProgrammer Feb 24 '15 at 02:32

5 Answers5

6

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • but the result of printing shows that it is in the same folder as my program, where I expect it to be. – Jeremy Fisher Feb 24 '15 at 02:26
  • @JeremyFisher Then either the file isn't in that folder, or you've got some other code that does something creative with the open file handle.... do you "delete" the file too? – Elliott Frisch Feb 24 '15 at 02:27
2

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

chrisinmtown
  • 3,571
  • 3
  • 34
  • 43
0

File needs to be in the class path and not in the source path. Copy the file in output/class files folder and it should be available.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • how would i transfer it to the class path, or even know where the class path is located? – Jeremy Fisher Feb 24 '15 at 02:29
  • No, it doesn't. `File f = new File("file.txt");` says that the file should be in the current "working" directory. `File` does not search the classpath for files...in fact, it doesn't search anywhere – MadProgrammer Feb 24 '15 at 02:30
  • He's not using getResourceFromStream() so I'm really puzzled about the comment about putting this little data file into the class path. – chrisinmtown Feb 24 '15 at 02:33
  • If only filename/relative path is used then file is looked into the directory/relative directory to the class files and not the source files. Hence was the answer. – Juned Ahsan Feb 24 '15 at 02:55
0

You should probably check out this question: Java can't find file when running through Eclipse

Basically you need to be sure where the execution is taking place (current directory) and how your SO will resolve the relative paths. Try changing the working directory in Eclipse' Run Configurations>Arguments or provide the absolute filename

Community
  • 1
  • 1
delephin
  • 1,085
  • 1
  • 8
  • 10
0

I'm extremely late to responding to this question, but I see that this is still an extremely hot topic to this day. It may not seem obvious, but what you want to use here is actually the newer file-handling i/o library, java.nio. The below explained example shows how to read a String from a file path, but I encourage you to take a look at the docs if you have a different use.

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Files;

public static void main(String[] args) throws IOException {  
  Path path = Path.of("app/src/main/java/pkgname/file.txt");
  String content = Files.readString(path);
  System.out.println(content); // Prints file content
}

Okay, code done, now time for the explanation. I'll start off with the import statements. java.io.IOException is necessary for some exception-handling. (Sidenote: Do not omit the throws IOException and/or the IOException import. Otherwise Files.readString() may throw an error in your editor, which I'll get to shortly). The Path class import is necessary to actually get the file, and the Files class import is necessary for file operations.

Now, the main function itself. The first line receives a Path object representing a file for you to actually read/write. Here the question of path name arises, which is the basis of the question. I have seen other solutions that tell you to take the absolute path of your file, but don't do that! It's extremely bad practice, especially with open-source or public code. Path.of actually allows you to use the path relative to your root folder (unless it isn't in a directory, simply inputting the file name does not work, I'm afraid). The example path name I gave is an example of a Gradle project. Next line, we get the content of the file as a String using a method from Files. Again, if you have a different use for a file, you can check the docs (a different method from the Files class will probably work for you). On the final line, we print the result. Hooray! Our output is just what we needed.

There you have it, using Path instead of File is the solution to this annoying bug. Hopefully this helps!

eEeEeE
  • 63
  • 1