字符流:
常识:在java中一个字符等于两个字节;
操作字符流的两个类:Writer,Reader
API文档介绍(Writer):
public abstract class Writer extends Object implements Appendable, Closeable, Flushable
发现此类依然是抽象类,如果使用子类还是需要使用该子类,FileWriter;
Writer类的常用方法:
关闭该流,但要先刷新它;
public abstract void close() throws IOException
刷新该流缓冲;
public abstract void flush() throws IOException
写入字符数组
public void write(char[] cbuf) throws IOException
写入字符数组的一部分
public abstract void write(char[] cbuf,int off,int len)throws IOException
写入字符串
public void write(String str) throws IOException
写入字符串的一部分
public void write(String str,int off,int len)throws IOException
FileWriter常用构造方法:
根据给定的 File 对象构造一个 FileWriter 对象
public FileWriter(File file)throws IOException
根据给定的文件名构造一个 FileWriter 对象
public FileWriter(String fileName)throws IOException
实例01: package cn.itcast04; import java.io.FileWriter; import java.io.IOException; public class FileWriterDemo01 { public static void main(String[] args) throws IOException { //创建IO对象 FileWriter fw = new FileWriter("d.txt" ); String s = "I love JAVA"; //写入字符串 fw.write( "Hello World"); //写入字符串的一部分 fw.write(s, 1,5); //写入字符数组 char[] chars = new char[]{ ‘a‘, ‘c‘, ‘b‘, ‘e‘}; fw.write(chars); //写入字符数组的一部分 fw.write(chars,0,3); fw.close(); } }
字符输入流(Reader)
API文档介绍(Reader):
public abstract class Reader extends Object implements Readable, Closeable
FileReader类常用方法:
构造方法:
根据给定的 File 对象构造一个 FileWriter 对象
public FileReader(File file)throws IOException
根据给定的文件名构造一个 FileWriter 对象
public FileReader(String fileName)throws IOException
常用方法:
读取单个字符:
public int read()throws IOException
将字符读入数组
public int read(char[] cbuf)throws IOException
读取数组中的一部分
public abstract int read(char[] cbuf,int off,int len)throws IOException
实例02: package cn.itcast04; import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileReaderDemo01 { public static void main(String[] args) throws IOException { File file= new File("d.txt" ); FileReader fr = new FileReader(file); //读取单个字符 int c; while((c=fr.read())!=-1) { System. out.println((char)c); } fr.close(); System. out.println("================================" ); File file2= new File("d.txt" ); FileReader fr2 = new FileReader(file2); //读入一个数组 char[] chars = new char[( int)file2.length()]; int len; while((len=fr2.read(chars))!=-1) { String s = new String(chars,0,len); System. out.println(s); } fr2.close(); } }