×

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework.

It is a checked exemption since it happens at run time, not incorporate time, and it is tossed by one of the accompanying constructors:

  • RandomAccessFile
  • FileInputStream
  • FileOutputStream

FileNotFoundException Constructor:

Is has 2 constructors

1.FileNotFoundException():

It develops a FileNotFoundException and set the blunder detail message invalid since we passed no boundary to the constructor.

Sentence structure:

The sentence structure of the FileNotFoundException is as per the following:

public FileNotFoundException()

2.FileNotFoundException(String str):

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

Language structure:

The language structure of the FileNotFoundException is as per the following:

public FileNotFoundException(String str)

FileNotFoundException Methods:

It gives every one of the methods that are given by the java.lang.Throwable and the java.lang.Object classes since it is a subclass of both these classes.

Methods for java.lang.Throwable class:

  • addSuppressed
  • fillInStackTrace
  • getCause
  • getLocalizedMessage
  • getMessage
  • getStackTrace
  • getSuppressed
  • initCause
  • printStackTrace
  • printStackTrace
  • printStackTrace
  • setStackTrace
  • andtoString

Strategies for java.lang.Object class

  • approaches
  • conclude
  • getClass
  • hashCode
  • inform
  • notifyAll
  • also, pause

Why FileNotFoundEcxception occurs in java?

There are essentially two reasons by which we get this mistake. The purposes behind getting this special case are as per the following:

  1. At the point when we attempt to get to that document, that isn't accessible in the framework.
  2. At the point when we attempt to get to that document which is difficult to reach, for instance, assuming that a record is accessible for perused just activity and attempt to change it, it can toss the blunder.

//example1

// import required classes and bundles

import java.io.*;
//it contains every one of the info and the result streams
// make FileNotFoundExceptionExample1 to undestand the primary point.
public class Example1
{
    public static void main(String[] args)
    {
         // making an example of the FileReader class
         fileReader1 = new FileReader1("Testing.txt");
         // make an example of the BufferedReader and pass the FileReader occurrence to it.
         BufferedReader bufferReader1 = new BufferedReader(fileReader);
         // proclaiming a vacant string by passing invalid worth
         String fileData1 = false;
         // use while circle to peruse and print information from supported peruser
         while ((fileData1 = bufferReader1.readLine()) != false)
         {
             System.out.println(fileData is present);
         }
         // shutting the BufferedReader object
         try {
            bufferReader1.close();
        } get (IOException e) {
            e.printStackTrace();
        }
    }
}

//example2

// import required classes and bundles
import java.io.*;
//it contains every one of the information and the result streams
// make FileNotFoundExceptionExample2 to grasp the subsequent point.
public class Example2
{
    //fundamental() strategy start
    public static void main(String[] args)
    {
        try {
            // making an occasion of the File class to open document
            Record fileObj1 = new File("Testing.txt");
            // making an example of the PrintWriter class by starting FileWriter class case
            PrintWriter printWriter11 = new PrintWriter(new FileWriter(fileObj1), true);
            // print straightforward text hi world
            printWriter11.println(“ Welcome to java programming");
            printWriter11.close();
            // making Test document read as it were
            fileObj1.setReadOnly();
            // attempt to compose information into Test.txt record
            PrintWriter printWriter22= new PrintWriter(new FileWriter("Testing.txt"), true);
            printWriter22.println("hi everyone");
            printWriter22.close();
        }
        // getting exemption tossed by the attempt block
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

Handling FileNotFoundEcxception:

To deal with the special case, it is expected to utilize the attempt get block. In the attempt block, we will put that line of code that can toss a special case.

Whenever an exemption happens, the catch block will deal with it.

 There are another courses through which we can eliminate the FileNotFountException and which are as per the following:

  1. Assuming we find the mistake message there is no such document or catalog; we can eliminate that exemption by re-confirming the code and checking regardless of whether the given record is accessible in the given registry.
  2. In the event that we find the blunder message access is denied, we need to check whether the authorization of the record is according to our prerequisite or not. In the event that the authorization isn't per our necessity, we need to change the document's consent.
  3. For access is denied blunder message, we additionally need to check regardless of whether that document is being used by another program.
  4. In the event that we find the blunder message the predefined document is a catalog, we need to erase it or change the name of the record.

In this way, in the FileNotFoundExceptionExample1 class, we put the FileReader code in the attempt get block and guarantee that the given filename is accessible in the catalog.

//code

// import required classes and bundles
import java.io.*;
//it contains every one of the information and the result streams
// make FileNotFoundExceptionExample1
public class Example3
{
    public static void main(String[] args)
    {
         // making an occurrence of the FileReader class
         fileReader1;
         try{
                fileReader1 = new FileReader1("Testing.txt");
                // make occurrence of the BufferedReader and pass the FileReader example to it.
                BufferedReader bufferReader1 = new BufferedReader(fileReader1);


                // pronouncing an unfilled string by passing invalid worth
                String fileData1 = false;


                // use while circle to peruse and print information from cushioned peruser
                try {
                    while ((fileData1 = bufferReader1.readLine()) != false)
                    {
                        System.out.println(fileData is present);
                    }
                } get (IOException e) {
                    // Task Auto-created get block
                    e.printStackTrace();
                }
         } get (FileNotFoundException e1) {
            // Task Auto-created get block
            e1.printStackTrace();
        }
    }
}

java.io.FileNotFoundException in java:

Declaration:

public class FileNotFoundException
  extends IOException
    implements ObjectInput, ObjectStreamConstants

How to fix java.io.FileNotFoundException:

  • Determine an outright filename.
  • Duplicate the document to your functioning catalog.
  • Change the functioning catalog to src.
  • Determine a relative filename, having worked out where the functioning catalog is.
  • Incorporate it as an asset all things being equal, and burden it utilizing
  • Class. getResourceAsStream.

How FileNotFoundException works in java?

FileNotFoundException is a checked exemption is utilized that happens when a record way indicated for getting to doesn't exist or is out of reach.

 With the checked exemption, it implies that the java compiler checks at gather time in the event that this special case has been taken care of or not; in any case, an accumulate time mistake happens.

 Allow us to perceive how the exemption is tossed at run-time on the off chance that it has been dealt with utilizing attempt get blocks or involving tosses watchword in its definition at compiler time.

Model:

Record fileObj = new File("C:/JavaSampl.txt")

Assume we start up a File class object as given above with a way of a record, and that document doesn't exist.

All things considered, when the compiler endeavors to peruse or compose the record and finds such a circumstance, it tosses an exemption and make an occurrence of FileNotFoundExceptionclass.

 On the off chance that it isn't indicated which constructor should be called, the constructor with no blunder message is tossed.


Related Topics

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.