Java says FileNotFoundException but file exists
Asked Answered
B

14

66

I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am having problems with the file reading. The instructor said to use this syntax

Scanner scores = new Scanner(new File("scores.dat"));

However, this throws a FileNotFoundException, but I have checked over and over again to see if the file exists in the current folder, and after that, I figured that it had to do something with the permissions. I changed the permissions for read and write for everyone, but it still did not work and it still keeps throwing the error. Does anyone have any idea why this may be occurring?

EDIT: It was actually pointing to a directory up, however, I have fixed that problem. Now file.exists() returns true, but when I try to put it in the Scanner, it throws the FileNotFoundException

Here is all my code

import java.util.Scanner;
import java.io.*;
public class readInt{
        public static void main(String args[]){
                File file = new File("lines.txt");
                System.out.println(file.exists());
                Scanner scan = new Scanner(file);
        }
}
Beltz answered 10/10, 2013 at 22:58 Comment(8)
What is current directory? Try printing new File(".")Klaxon
Print the path of new File("scores.dat") and double-check to see if it exists in the expected directory.Orphaorphan
@Klaxon it is searching in the correct directory, and it is giving the correct absolute path, however, the file is still not foundBeltz
Is this on a Unix machine? If so, please post the output of ls -la from the directory where you're running java.Peeler
More stuff to try out: What does new File("scores.dat").exists() return? What does new File(".").listFiles() returns? Do you find your file in the list? If you pick that instance, does it work with the scanner?Klaxon
What is the text of the exception?Kolyma
It's almost certain that you're in the wrong directory. Print new File("scores.dat").getAbsolutePath() and make sure the file's really in that location.Ceramist
just as a side note, I was getting this error by calling new File().getName() instead of new File().getAbsolutePath(), even though getName() returned the correct path, it did not include file: at the beginning of the String.Barela
W
96

There are a number situation where a FileNotFoundException may be thrown at runtime.

  1. The named file does not exist. This could be for a number of reasons including:

    • The pathname is simply wrong
    • The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
    • The pathname is relative, and it doesn't resolve correctly relative to the actual current directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
    • The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
  2. The named file is actually a directory.

  3. The named file cannot be opened for reading for some reason.

The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:

  • Calling file.exists() will tell you if any file system object exists with the given name / pathname.

  • Calling file.isDirectory() will test if it is a directory.

  • Calling file.canRead() will test if it is a readable file.

  • This line will tell you what the current directory is:

      System.out.println(new File(".").getAbsolutePath());
    
  • This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trailing whitespace:

      System.out.println("The path is '" + path + "'");
    

    Look for unexpected spaces, line breaks, etc in the output.


It turns out that your example code has a compilation error.

I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

If you change your code to the following, it will fix that problem.

public static void main(String[] args) throws FileNotFoundException {    
    File file = new File("scores.dat");
    System.out.println(file.exists());
    Scanner scan = new Scanner(file);
}

Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.

Wilmott answered 11/10, 2013 at 2:12 Comment(3)
Your third case includes the other two, and also includes a number of other easily separable cases such as permission problems, network failures, etc., which isn't very enlightening, and doesn't make any kind of a case for there being 'three cases'. Testing File.canRead() is futile when you already have to catch an exception, and wasteful when the system has to test it anyway during the open.Kolyma
If the issue occurs on MacOS, it could be because Java or Android Studio/your IDE doesn't have access to the Documents folder. This can be fixed in Settings/Security& Privacy/Files and Folders (or Full Disk Access)Elna
Well, File.canRead() can test the problem. When you find the solution, just remove it. For me, it is also a silly problem. I worked in springboot project. My path in application-dev.properties is my.path="/etc/my/path/file.conf". The problem is the double quote. So, when I print the path in my program, the result looks good. That is:The pathname looks correct but is actually wrong. Just remove the double quote, and everything works fine.Abney
S
57

The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.

Use this line and see where the path is:

System.out.println(new File(".").getAbsoluteFile());
Soapy answered 10/10, 2013 at 23:3 Comment(0)
W
20

It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".

Weissberg answered 8/5, 2015 at 2:18 Comment(1)
Yes, that was the real culprit. "Hide file extensions for known file types" is checked and unfortunately my file was having a redundant extension.Lungan
D
10

I recently found interesting case that produces FileNotFoundExeption when file is obviously exists on the disk. In my program I read file path from another text file and create File object:

//String path was read from file
System.out.println(path); //file with exactly same visible path exists on disk
File file = new File(path); 
System.out.println(file.exists());  //false
System.out.println(file.canRead());  //false
FileInputStream fis = new FileInputStream(file);  // FileNotFoundExeption 

The cause of the problem was that the path contained invisible \r\n characters at the end.

The fix in my case was:

File file = new File(path.trim()); 

To generalize a bit, the invisible / non-printing characters could have include space or tab characters, and possibly others, and they could have appeared at the beginning of the path, at the end, or embedded in the path. Trim will work in some cases but not all. There are a couple of things that you can help to spot this kind of problem:

  1. Output the pathname with quote characters around it; e.g.

      System.out.println("Check me! '" + path + "'");
    

    and carefully check the output for spaces and line breaks where they shouldn't be.

  2. Use a Java debugger to carefully examine the pathname string, character by character, looking for characters that shouldn't be there. (Also check for homoglyph characters!)

Diamine answered 11/8, 2016 at 7:55 Comment(0)
M
6

Move the files out of src and into the main folder of the project.

Muscadine answered 21/10, 2018 at 11:4 Comment(0)
P
4

Reading and writing from and to a file can be blocked by your OS depending on the file's permission attributes.

If you are trying to read from the file, then I recommend using File's setReadable method to set it to true, or, this code for instance:

String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file;
File f = new File(arbitrary_path);
f.setReadable(true);
data_of_file = Files.readAllBytes(f);
f.setReadable(false); // do this if you want to prevent un-knowledgeable 
                      //programmers from accessing your file.

If you are trying to write to the file, then I recommend using File's setWritable method to set it to true, or, this code for instance:

String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
File f = new File(arbitrary_path);
f.setWritable(true);
Files.write(f, byte_array);
f.setWritable(false); // do this if you want to prevent un-knowledgeable 
                      //programmers from changing your file (for security.)
Pegg answered 7/7, 2017 at 12:57 Comment(0)
D
2

If you are reading the path through Scanner or through command line args, instead of copy pasting the path directly from Windows Explorer just manually type in the path.

Downhill answered 27/5, 2017 at 13:59 Comment(0)
S
0

I had this same error and solved it simply by adding the src directory that is found in Java project structure.

String path = System.getProperty("user.dir") + "\\src\\package_name\\file_name";
File file = new File(path);
Scanner scanner = new Scanner(file);

Notice that System.getProperty("user.dir") and new File(".").getAbsolutePath() return your project root directory path, so you have to add the path to your subdirectories and packages

Seafood answered 11/5, 2019 at 16:56 Comment(2)
While this worked for you, there are problems with this approach. 1) You are making your application platform dependent by using Windows-specific pathname syntax. 2) You are assuming that your code is going to be executed with the current directory set to the build directory (or something). That won't work when you ship the code to someone else.Duvetyn
If the file you are trying to read is part of your source code base, a better idea is to copy it into your JAR file (or the file tree containing your compiled classes) and use getResourceAsStream to find it via the (runtime) classpath.Duvetyn
F
0

You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.

Fowkes answered 3/1, 2020 at 15:40 Comment(0)
S
0

Use single forward slash and always type the path manually. For example:

FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");
Spillage answered 21/2, 2020 at 5:56 Comment(0)
A
0

What worked for me was catching the exception. Without it the compiler complains even if the file exists.

InputStream file = new FileInputStream("filename");

changed to

try{
    InputStream file = new FileInputStream("filename");
    System.out.println(file.available());
}
catch (Exception e){
    System.out.println(e);
}
Ambriz answered 8/3, 2021 at 8:31 Comment(0)
F
0

This works for me. It also can read files such txt, csv and .in

public class NewReader {

    public void read() throws FileNotFoundException, URISyntaxException {
        File file = new File(Objects.requireNonNull(NewReader.class.getResource("/test.txt")).toURI());
        Scanner sc = new Scanner(file);

        while (sc.hasNext()) {
            String text = sc.next();
            System.out.println(text);

        }
    }
}

the file is located in resource folder generated by maven. If you have other folders nested in, just add it to the file name like "examples/test.txt".

Farad answered 25/4, 2022 at 11:57 Comment(0)
C
0

Kinda weird, I still don't understand why but it worked for me : I just surrounded my 'Scanner sc=new Scanner(new File("your/path"));' in a try catch block and while still in the try block I can access the file

Crandale answered 16/11, 2023 at 7:43 Comment(1)
It would be nice if you would please share the code so that others can be helped by your find... thxPirouette
I
0

I moved the text file outside of the src folder and then it worked. I thought it was supposed to work in the src folder but apparently not.

Intensifier answered 22/11, 2023 at 23:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.