Java file doesn exist exception



java.io.FileNotFoundException in Java

java.io.FileNotFoundException which is a common exception which occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors RandomAccessFile, FileInputStream, and FileOutputStream. FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn’t occur.

Declaration :

Constructors :

  • FileNotFoundException() : It gives FileNotFoundException with null message.
  • FileNotFoundException(String s) : It gives FileNotFoundException with detail message.

It doesn’t have any methods. Now let’s understand the hierarchy of this class i.e FileNotFoundException extends IOException which further extends the Exception class which extends the Throwable class and further the Object class.

Hierarchy Diagram:

Why this Exception occurs?

There are mainly 2 scenarios when FileNotFoundException occurs. Now let’s see them with examples provided:

  1. If the given file is not available in the given location then this error will occur.
  2. If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file, if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.

Scenario 1:

If the given file is not available in the given location then this error will occur.

Example:

Output

Scenario 2:

If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.

Example:

Output

Handling Exception:

Firstly we have to use the try-catch block if we know whether the error will occur. Inside try block all the lines should be there if there are chances of errors. There are other remedies to handle the exception:

  1. If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not.
  2. If the message of the exception tells us that access is denied then we have to check the permissions of the file (read, write, both read and write) and also check whether that file is in use by another program.
  3. If the message of the exception tells us that the specified file is a directory then you must either delete the existing directory(if the directory not in use) or change the name of the file.

Источник

How to Fix the FileNotFoundException in Java.io

Table of Contents

The java.io.FileNotFoundException is a checked exception in Java that occurs when an attempt to open a file denoted by a specified pathname fails. This exception is thrown by the FileInputStream , FileOutputStream , and RandomAccessFile constructors when a file with the specified pathname either does not exist or is inaccessible.

Since FileNotFoundException is a checked exception, it must be explicitly handled in methods which can throw this exception — either by using a try-catch block or by throwing it using the throws clause.

What Causes FileNotFoundException

There are two main scenarios when the FileNotFoundException occurs:

  • If a file with the specified pathname does not exist.
  • If a file with the specified pathname is inaccessible, for example, if the file is read-only and is attempted to be opened for writing.
Читайте также:  Error job failed prepare environment exit status 1

FileNotFoundException Example

Here’s an example of a FileNotFoundException thrown when trying to access a file that does not exist in the system:

In the above example, a file with the name myfile.txt is attempted to be accessed. However, since no such file exists in the system, a FileNotFoundException is thrown:

How to Fix FileNotFoundException

Since FileNotFoundException is a checked exception, a try-catch block should be used to handle it. The try block should contain the lines of code that can throw the exception and the catch block should catch and handle the exception appropriately.

Some ways to fix the exception are:

  • If the message of the exception indicates that no such file or directory exists, the file pathname should be checked again to ensure it is correct and if the file exists at the specified location.
  • If the message indicates that access is denied, the permissions of the file should be verified and whether the file is in use by another program.
  • If the message indicates that the specified file is a directory, the name of the file should be changed or the existing directory should be deleted if not in use.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Источник

FileNotFoundException in Java

FileNotFoundException is another exception class available in the java.io package. The exception occurs when we try to access that file which is not available in the system. It is a checked exception because it occurs at run time, not compile-time, and it is thrown by one of the following constructors:

  1. RandomAccessFile
  2. FileInputStream
  3. FileOutputStream

FileNotFoundException Constructor

FileNotFoundException class has the following two constructors:

1. FileNotFoundException()

It constructs a FileNotFoundException and set the error detail message null because we didn’t pass any parameter to the constructor.

Syntax:

The syntax of the FileNotFoundException is as follows:

2. FileNotFoundException(String str)

It constructs a FileNotFoundException and set the error detail message str, which we pass to the constructor.

Syntax:

The syntax of the FileNotFoundException is as follows:

FileNotFoundException Methods

It provides all the methods that are provided by the java.lang.Throwable and the java.lang.Object classes because it is a subclass of both these classes.

Methods of java.lang.Throwable class

Methods of java.lang.Object class

To learn more about these methods, visit the following:

Why FileNotFoundException occurs?

There are mainly two reasons by which we get this error. The reasons for getting this exception are as follows:

  1. When we try to access that file, that is not available in the system.
  2. When we try to access that file which is inaccessible, for example, if a file is available for read-only operation and try to modify it, it can throw the error.

Let’s takes some examples and understand both the above points one by one:

Читайте также:  Brother hl 2132r error сброс

FileNotFoundExample1.java

Output:

FileNotFoundExample2.java

Output:

Handling FileNotFoundException

In order to handle the exception, it is required to use the try-catch block. In the try block, we will put that line of code that can throw an exception. Whenever an exception occurs, the catch block will handle it. There are some other ways through which we can remove the FileNotFountException and which are as follows:

  1. If we find the error message there is no such file or directory; we can remove that exception by re-verifying the code and checking whether the given file is available in the given directory or not.
  2. If we find the error message access is denied, we have to check whether the permission of the file is as per our requirement or not. If the permission is not per our requirement, we have to modify the file’s permission.
  3. For access is denied error message, we also have to check whether that file is in use by another program or not.
  4. If we find the error message the specified file is a directory, we have to delete it or change the name of the file.

So, in the FileNotFoundExceptionExample1 class, we put the FileReader code in the try-catch block and ensure that the given filename is available in the directory.

Источник

Handle FileNotFoundException in Java

FileNotFoundException occurs when we are trying to access a file. It is a part of IO exceptions thrown by FileOutputStream, FileInputStream, and RandomAccessFile, and we can use try-catch blocks to handle these exceptions.

This tutorial describes the FileNotFoundException and demonstrates how to handle FileNotFoundException.

the Java IO FileNotFoundException

The FileNotFoundException occurs when a file with a particular pathname does not exist, or the file with pathname exists, but we can access it for some reason. The FileNotFoundException extends the java.io.IOException, which extends java.lang.Exception, which is dealt with try-catch blocks.

The picture below demonstrates the structure of FileNotFoundException .

Let’s run an example to see the FileNotFoundException :

The file demo.txt doesn’t exist; the code will throw the FileNotFoundException.

Handle FileNotFoundException in Java

We can use try-catch blocks to handle the FileNotFoundException in Java. The example below demonstrates the handling of FileNotFoundException:

The code above handles the exception. First, it tries to open and read the file, and if the file does not exist or is not permitted to open and read, it will throw the FileNotFoundException.

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

Источник

FileNotFoundException in Java

FileNotFoundException is a checked exception therefore we must catch or handle it. It is a subclass of IOException and is defined in the java.io package. Generally, FileNotFoundException will be thrown by the FileInputStream, FileReader, and RandomAccessFile constructors, where file information is the source and must be passed to the constructor. Here we will discuss the different reasons for getting this exception.

Unhandled exception type FileNotFoundException

FileNotFoundException is a checked exception, and at compile time compiler checks whether we are handling FileNotFoundException or not.

Читайте также:  Что такое download failed please try again error code 291

It means if there is a chance to raise FileNotFoundException in the statement then we must handle the FileNotFoundException either by using try-catch block or by using the throws keyword.

Unreported Exception FileNotFoundException; must be caught or declared to be thrown

If we don’t handle FileNotFoundException then the compiler gives the compile-time error: unreported exception FileNotFoundException; must be caught or declared to be thrown.

Example:- FileReader class is used to read character data from the file. The constructor of FileReader class throws FileNotFoundException.

Since we don’t handle FileNotFoundException therefore we will get the compile-time error:- unreported exception FileNotFoundException; must be caught or declared to be thrown,

FileReaderDemo.java:6: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(“data.txt”);
^
1 error

Solution of compile-time error: unreported exception FileNotFoundException; must be caught or declared to be thrown,

  • Catch this exception using try/catch block
  • Handle this exception using throws

But before catching and handling the exception we must import FileNotFoundException or java.io package. While catching or handling the exception we can also use superclass exception, Exception, or Throwable. The Throwable is the superclass for all Exceptions.

Using throws we are informing the caller method that the called method may throw FileNotFoundException. Now, it’s the responsibility of the caller method to catch or handle the exception.

Using try/catch block we are catching the exception. We can finally block to close the stream also.

Different Reasons to Get FileNotFoundException in Java

We will get runtime exception in the following cases,

  • The passed named File is not available.
  • Available but it is a directory rather than a normal file.
  • The file doesn’t have reading/writing permission.
  • Access permission is not there.

If the given name is a directory/folder, not a file then also we will get the same exception with “Access is denied”.

In all Writer and Output classes, we won’t get FileNotFoundException because the file is not available. These classes are made for writing the data and need destination file information, if the file is not available then their constructors can create an empty file with the given name itself, and then write the data into the file. They are FileNotFoundException for another reason like file creation permission is not there, it is available but represents directory/folder, or file is available but writing permission is not there.

Most of the time, Windows C drive doesn’t allow to create a file, it only gives permission to create a directory. In this case, we can get FileNotFoundException. We can get an exception:- Exception in thread “main” java.io.FileNotFoundException: C:\xyz.txt (Access is denied). Similarly, in Linux/Unix OS, we can’t create files in other user directories.

In all Reader and Input classes file is the source from where the Java application will collect the data. And in this case, the file must be available else we will get FileNotFoundException. Other reasons are:- it is a folder rather than a file, access permission is not there.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Оцените статью
toolgir.ru
Adblock
detector