📜  Java I/O-FileReader类

📅  最后修改于: 2020-09-27 04:48:51             🧑  作者: Mango

Java FileReader类

Java FileReader类用于从文件读取数据。它以字节格式返回数据,例如FileInputStream类。

它是面向字符的类,用于Java中的文件处理。

Java FileReader类声明

让我们看一下Java.io.FileReader类的声明:

public class FileReader extends InputStreamReader

FileReader类的构造方法

Constructor Description
FileReader(String file) It gets filename in string. It opens the given file in read mode. If file doesn’t exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file doesn’t exist, it throws FileNotFoundException.

FileReader类的方法

Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
void close() It is used to close the FileReader class.

Java FileReader示例

在此示例中,我们使用Java FileReader类从文本文件testout.txt中读取数据。

package com.javatpoint;

import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{  
  FileReader fr=new FileReader("D:\\testout.txt");  
  int i;  
  while((i=fr.read())!=-1)  
  System.out.print((char)i);  
  fr.close();  
}  
}  

在这里,我们假设您在“ testout.txt”文件中包含以下数据:

Welcome to javaTpoint.

输出:

Welcome to javaTpoint.