FileReader(File, Charset): This method is available in the java.io.FileReader class of Java.
Syntax:
java.io.FileReader.FileReader(File file, Charset charset) throws IOException
This method takes two arguments. This method creates a new FileReader, given the File to read and the charset.
Parameters: Two parameters are required for this method.
file: the File to read.
charset: the charset.
Throws:
IOException - 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.FileReader;import java.io.IOException;import java.nio.charset.Charset;public class FileReader4 {public static void main(String[] args) {String pathname = "D:\\hello.txt";File file = new File(pathname);Charset charset = Charset.defaultCharset();FileReader fileReader = null;try {fileReader = new FileReader(file, charset);} catch (IOException e) {System.out.println("File does not exist");return;}System.out.println(fileReader);}}
Output:
java.io.FileReader@7637f22
Approach 2: IOException
Java
import java.io.File;import java.io.FileReader;import java.io.IOException;import java.nio.charset.Charset;public class FileReader4 {public static void main(String[] args) {String pathname = "D:\\hello2.txt";File file = new File(pathname);Charset charset = Charset.defaultCharset();FileReader fileReader = null;try {fileReader = new FileReader(file, charset);} catch (IOException e) {System.out.println("File does not exist");return;}System.out.println(fileReader);}}
Output:
File does not exist
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