字符流

字符流用于处理用ASCII字符集或Unicode(包含ASCII的国际字符集)表示的文本,可以用字符流来处理的文件有纯文本文件,HTML文档,和java源代码文件。用于读写这些流的类都是Reader和Writer的子类,对于所有的文本输入,都应使用字符流来处理,而不能直接使用字节流来处理。

字符的继承关系

java-io流-字符流

读写文件

FileReader是InputStreamReader的子类,常用于从文件中读取字符流。FileWriter为OutputStreamWriter的子类,常用于向文件中写字符流。

文件中读写

构造方法

public FileReader(File file)  throws FileNotFoundException
public FileReader(String fileName) throws FileNotFoundException
public FileWriter(File file) throws IOException
       根据给定的 File 对象构造一个 FileWriter 对象。 
public FileWriter(File file, boolean append) throws IOException
       根据给定的 File 对象构造一个 FileWriter 对象。 
public FileWriter(String fileName) throws IOException
       根据给定的文件名构造一个 FileWriter 对象。 
public FileWriter(String fileName, boolean append) throws IOException
       根据给定的文件名以及指示是否附加写入数据的 boolean 值来构造 FileWriter 对象。

1、在给定指定文件名或者指定的文件的情况下读写数据
2、FileNotFoundException -如果文件不存在,或者它是一个目录,而不是一个常规文件,抑或因为其他某些原因而无法打开进行读取
3、IOException - 如果该文件存在,但它是一个目录,而不是一个常规文件;或者该文件不存在,但无法创建它;抑或因为其他某些原因而无法打开它

 private static Reader testReader = null;
    private static Writer testWriter = null;
    private static String readFilePath = "C:/Users/asus-pc/Desktop/javaProject/src/testIoChar/IoCharDemo.java";
	private static String writeFilePath = "C:/Users/asus-pc/Desktop/javaProject/src/testIoChar/IoCharDemo2.java";
    public static void main(String[] args) throws IOException {
		  File  file  = new File(readFilePath);
	       testReader = new FileReader(file);
          //testReade = new FileReader(filePath);
	       //两种构造方法都可以
	       testWriter = new FileWriter(writeFilePath);//重写文件
	       //testWriter = new FileWriter(writeFilePath,true);在文件尾追加数据
	       }

常用方法概述

从类 java.io.InputStreamReader 继承的方法 
close, getEncoding, read, read, ready 
  从类 java.io.Reader 继承的方法 
mark, markSupported, read, read, reset, skip 

常用方法与字节操作相同

package testIoChar;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class IoCharDemo {
    private static Reader testReader = null;
    private static Writer testWriter = null;
    private static String readFilePath = "C:/Users/asus-pc/Desktop/javaProject/src/testIoChar/IoCharDemo.java";
	private static String writeFilePath = "C:/Users/asus-pc/Desktop/javaProject/src/testIoChar/IoCharDemo2.java";
    public static void main(String[] args) throws IOException {
		  File  file  = new File(readFilePath);
	       testReader = new FileReader(file);
          //testReade = new FileReader(filePath);
	       //两种构造方法都可以
	       testWriter = new FileWriter(writeFilePath);
	       char[]ch = new char[(int)file.length()];
	       testReader.read(ch);
	       System.out.println(new String(ch));
	       testWriter.write(new String(ch));
	       testReader.close();
	       testWriter.close();
	       //如果没有关闭,会发现文件中没有数据,因为没有刷新流,数据只是写在了流里
	       //close()方法中调用了flush()。
    }
}

相关文章: