FileReader FileReader(String, Charset) in Java

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

Syntax:

java.io.FileReader.FileReader(String fileName, Charset charset) throws IOException

This method takes two arguments. This method creates a new FileReader, given the name of the file to read and the charset.

Parameters: Two parameters are required for this method.

fileName: the name of the file to read.

charset: the charset.

Throws:

IOException - if the named 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.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;

public class FileReader5 {
    public static void main(String[] args) {

        String fileName = "D:\\hello.txt";

        Charset charset = Charset.defaultCharset();
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(fileName, charset);
        } catch (IOException e) {
            System.out.println("File not present");
            return;
        }

        System.out.println(fileReader);

    }
}

Output:

java.io.FileReader@7637f22


Approach 2: IOException 

Java

import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;

public class FileReader5 {
    public static void main(String[] args) {

        String fileName = "D:\\hello2.txt";

        Charset charset = Charset.defaultCharset();
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(fileName, charset);
        } catch (IOException e) {
            System.out.println("File not present");
            return;
        }

        System.out.println(fileReader);

    }
}

Output:

File not present


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