java 字符流 FileReader FileWriter

一、FileReader

1、概念

字符输入流,硬盘->内存

2、构造

new FileReader(字符串)
new FileReader(file对象)

3、方法

//1.read(),一个一个字符读取,返回值字符的数字
//2.read(char[] ), 字符数组读取,返回值读取的长度
//3.close(),关闭字符流

4、异常处理

try(IO对象){

}catch(){
异常
}
// 不用手动关闭IO流

5、案例,读取字符数组

package com.wt.chars;

import java.io.FileReader;
import java.io.IOException;

public class Demon01 {
    public static void main(String[] args) {
        try(FileReader fr = new FileReader("module3\\3.txt");) {
            char[] chars = new char[1024];
            int len;
            while ((len=fr.read(chars))!=-1){
                System.out.println(new String(chars, 0, len));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

二、FileWriter

1、概念

字符输出流,内存->硬盘

2、构造

// 1.FileWriter(字符串);
// 2.FileWriter(file对象);
// 3.FileWriter(字符串, true),追加

3、方法

write(字符串),写入字符串
write(字符串, off, len),写入部分字符串 
write(char[]),写入字符数组
write(char[], off, len),写入部分字符数组
write(),写入单个字符
flush() 刷新,把内容刷到硬盘
close() 关闭IO流

4、异常处理

try(IO流对象){

}catch(){

}

5、案例

package com.wt.chars;

import java.io.FileWriter;
import java.io.IOException;

public class Demon02 {
    public static void main(String[] args) {
        try (FileWriter fw = new FileWriter("module3\\3.txt");){
            String str = "江山雾笼烟雨遥,\n十年一剑斩皇朝。";
            fw.write(str);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

 

posted @ 2025-04-20 10:00  市丸银  阅读(15)  评论(0)    收藏  举报