FileReader 和 FileWriter 是字符流,即按照字符来操作 I/O 。
示例代码
import java.io.FileReader;import java.io.IOException;public class Main {public static void main(String[] args) {// readFile01();readFile02();}// 一次读取 1 个字符public static void readFile01() {String path = "./hello.txt";FileReader freader = null;int temp;try {freader = new FileReader(path);while ((temp = freader.read()) != -1) {System.out.print((char) temp);}} catch (IOException e) {e.printStackTrace();} finally {// 关闭流try {freader.close();} catch (IOException e) {e.printStackTrace();}}}// 一次读取 1024 个字符public static void readFile02() {String path = "./hello.txt";FileReader freader = null;int readLen = 0;char[] buffer = new char[1024];try {freader = new FileReader(path);while ((readLen = freader.read(buffer)) != -1) {System.out.print(new String(buffer, 0, readLen));}} catch (IOException e) {e.printStackTrace();} finally {// 关闭流try {freader.close();} catch (IOException e) {e.printStackTrace();}}}}
