FileReader FileReader(File) in Java

FileReader(File): This method is available in the java.io.FileReader class of Java.

Syntax:

java.io.FileReader.FileReader(File file) throws FileNotFoundException

This method takes one argument. This method creates a new FileReader, given the File to read, using the platform's default charset.

Parameters: One parameter is required for this method.

file: the File to read.

Throws:

FileNotFoundException - if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

Approach 1: When no exception

Java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FileReader1 {
    public static void main(String[] args)
throws FileNotFoundException {

        String pathname = "D:\\hello.txt";
        File file = new File(pathname);
        FileReader fileReader = new FileReader(file);

        System.out.println(fileReader);

    }
}

Output:

java.io.FileReader@7637f22


Approach 2: FileNotFoundException

Java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FileReader1 {
    public static void main(String[] args)
throws FileNotFoundException {

        String pathname = "D:\\hello2.txt";
        File file = new File(pathname);
        FileReader fileReader = new FileReader(file);

        System.out.println(fileReader);

    }
}

Output:

Exception in thread "main" java.io.FileNotFoundException: D:\hello2.txt (Access is denied) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:211) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:153) at java.base/java.io.FileReader.<init>(FileReader.java:75)


Some other methods of FileReader

FileReader(File)This method creates a new FileReader, given the File to read, using the platform's default charset.

FileReader(FileDescriptor)This method creates a new FileReader, given the FileDescriptor to read, using the platform's default charset.

FileReader(String)This method creates a new FileReader, given the name of the file to read, using the platform's default charset.

FileReader(File, Charset)This method creates a new FileReader, given the File to read and the charset.

FileReader(String, Charset)This method creates a new FileReader, given the name of the file to read and the charset.

No comments:

Post a Comment