字符流操作文件
概述
程序开发中,经常需要对文本内容进行读取和输出。读取字符,可以使用字符输入流FileReader。写入字符,可以使用FileWriter。
FileWriter
FileWriter的使用同FileInputStream基本一样,代码如下:
public static void main(String[] args){
FileWriter writer = null;
try {
writer = new FileWriter("3.txt");
writer.write("天青色等烟雨");
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (writer != null){
writer.close();
}
}catch (Exception e){
e.printStackTrace();
}
}//finally
}//main
运行结果展示如下:

追加模式同FileOutputStream基本一样,在构造方法的第二个参数传入true。
与字节流不一样的是,
字符流可以在构造方法的第二个参数传入字符集名称,指定流的字符集。
FileReader
FileReader的使用同FileInputStream基本一样,代码示例如下:
FileWriter writer = null;
FileReader reader = null;
try {
// writer = new FileWriter("3.txt");
// writer.write("天青色等烟雨而我");
reader = new FileReader("3.txt");
//读取第一个字符
int c = reader.read();
System.out.println((char)c);
//读第二个字符
int c2 = reader.read();
System.out.println((char)c2);
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (writer != null){
writer.close();
}
if (reader != null){
reader.close();
}
}catch (Exception e){
e.printStackTrace();
}
}//finally
运行结果如下:
天
青
也可以直接用循环读取字符,同字节流一样,字符流的read()方法读取8位字节返回0~255的整数,read(char[] c)将读取的内容保存到数组c中,返回读取的字符长度,读取完成返回-1,代码如下:
public static void main(String[] args){
FileWriter writer = null;
FileReader reader = null;
try {
// writer = new FileWriter("3.txt");
// writer.write("天青色等烟雨而我");
reader = new FileReader("3.txt");
int len = 0;
char[] chars = new char[3];
while (true){
len = reader.read(chars);
if (len == -1)
break;
System.out.println(chars);
// System.out.println(new String(chars,0,len));
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (writer != null){
writer.close();
}
if (reader != null){
reader.close();
}
}catch (Exception e){
e.printStackTrace();
}
}//finally
}//main
运行结果如下
天青色
等烟雨
而我雨
可以发现遇到了和之前FileInputStream一样的问题,因此我们在使用缓冲区时需注意:
使用new String(char[] c,int off,int len)或new String(byte[] b,int off,int len)构造方法截取数组中的有效数据。
浙公网安备 33010602011771号