一:字符流
一个字符等于两个字节,专门操作字符的类有:Reader 和 Writer。
1、字符输出流
Writer是一个字符流的输出类,也是一个抽象类,在操作文件的 时候就要使用子类:FileWriter。
范例1:
package haizhu.com;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
public class StreamDemo01 {
public static void main(String[] args) throws Exception{
File f = new File("d:"+File.separator+"test.txt");
Writer out = null;
out = new FileWriter(f);
String str = "Hello world";
out.write(str);
out.close();
}
}
整个程序与OutputStream的操作流程没有太大区别,唯一的好处就是可以直接输出字符串,而不用讲字符串转变为byte数组之后再输出。
追加内容和字节流一样,也是使用含有boolean append的构造方法:
范例2:
package haizhu.com;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
public class StreamDemo02 {
public static void main(String[] args) throws Exception{
File f = new File("d:"+File.separator+"test.txt");
Writer out = null;
out = new FileWriter(f,true); //增加boolean append
String str = "To be or not to be.";
out.write(str);
out.close();
}
}
2、字符输入流
读取文件:
范例3:
package haizhu.com;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
public class StreamDemo03 {
public static void main(String[] args) throws Exception{
File f = new File("d:"+File.separator+"test.txt");
Reader reader = null;
reader = new FileReader(f); //增加boolean append
char c[] = new char[(int)f.length()];
int len = reader.read(c);
reader.close();
System.out.println("长度是:"+len);
System.out.println("内容是:"+new String(c));
}
}