Search This Blog

Showing posts with label actually. Show all posts
Showing posts with label actually. Show all posts

Java FileNotFoundException While File is Existing There

Sometimes you my encounter a FileNotFoundException in java while you can see that the specified file is there. This can happen for several reasons.The java code may throw a  FileNotFoundException even when the file exists. This can be for different reasons.

Reason 1

The file does not exist really. Although you can see the file, the path you may have entered may be incorrect. For example, the following code may throw exception in some operating systems:

File f=new File("D:\myfile.txt");

This is because the file separator character is '\' in windows os. since \ is used to display non graphical characters like '\n' you should use its corresponding escape sequence. So "D:\\myfile.txt" would work on windows. If your java application is a cross platform program, you should consider using File.separator instead of '\\' because not all operating systems use '\\' as file separator character. So, the best approach is ;

File f=new File("D:"+File.separator+"myfile.txt");

File.separator is the system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely File.separatorChar. If you want to get this character as a Character itself, you can use File.separatorChar. There can be other mistakes in the path.

Reason 2

The name you entered as a file may be actually a directory. So an exception can be thrown in java when you try to read from or write to such File object.

Reason 3

You cannot open it for reading or writing for some other reasons. You can check the status of file by calling the methods like f.exists(), f.canRead(), f.canWrite(), f.isFile() and f.isDirectory(). All these methods return a boolean. I hope these java method names describe well what they are intended for.