Java IO之字符流

1. 字符流

在程序中一个字符等于两个字节,Java为我们提供了Reader和Writer两个专门操作字符流的类

Java IO之字符流

1) 字符输出流:Writer

Writer是一个字符流,它是一个抽象类,所以要使用它,也必须通过其子类来实例化它后才能使用它。

Writer类的常用方法

方法名称

描述

public abstract void close() throws IOException

关闭输出流

public void write(String str) throws IOException

将字符串输出

public void write(char cbuf) throws IOException

将字符数组输出

public abstract void flush() throws IOException

强制性清空缓存

示例1:HelloWorld

向一个文本文件中通过字符输出流写入数据

public static void main(String[] args) throws Exception { // 声明一个File对象 File file = new File("hellowolrd.txt"); // 声明一个Write对象 Writer writer = null; // 通过FileWriter类来实例化Writer类的对象并以追加的形式写入 writer = new FileWriter(file, true); // 声明一个要写入的字符串 String str = "字符串形式写入Helloworld"; // 写入文本文件中 writer.write(str); // 刷新 writer.flush(); // 关闭字符输出流 writer.close(); }


2) 字符输入流:Reader

Reader本身也是一个抽象类,同样,如果使用它,我们需要通过其子类来实例化它才可以使用它。

Reader类的常用方法

方法名称

描述

public abstract void close() throws IOException

public int read() throws IOException

public int read(char cbuf) throws IOException

通过方法我们看到Reader类只提供了一个读入字符的方法

示例2:还是Helloworld

在上面的基础上把文本中的内容读出来,并且显示在控制台上

public static void main(String[] args) throws Exception { // 声明一个File对象 File file = new File("hellowolrd.txt"); // 声明一个Reader类的对象 Reader reader = null; // 通过FileReader子类来实例化Reader对象 reader = new FileReader(file); // 声明一个字符数组 char[] c = new char[1024]; // // 将内容输出 // int len = reader.read(c); //循环方式一个一个读 int len=0; int temp=0; while((temp=reader.read())!=-1){ c[len]=(char)temp; len++; } // 关闭输入流 reader.close(); // 把char数组转换成字符串输出 System.out.println(new String(c, 0, len)); }


2. 字符流与字节流的区别

操作字节流操作时本身不会用到缓冲区,是文件本身直接操作,而字节流在操作时就使用到了缓冲区。

Java IO之字符流

如果我们在操作字符流的时候,不关闭流,我们写入的数据是无法保存的。所以在操作字符流的时候一定要记得关闭流