字符流FileReader与FileWriter

public class CharStream {
    public static void main(String[] args) {
        CharStream charStream = new CharStream();
        //1、字符输入流,表示把文件写入到硬盘中
        charStream.outPutStream("D:\\2.txt");
        //2、字符输出流,表示想硬盘读出文件显示出来
        charStream.inputStream("D:\\2.txt");
    }

    private void inputStream(String path) {
        File file = new File(path);
        if (!file.exists()) {
            IAssert.throwMsg("文件不存在:" + path);
        }

        //todo 下面两行都可以实现字节流读取
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(file);
        } catch (FileNotFoundException e) {
            IAssert.throwMsg("文件不存在:" + path);
        }

        try {
            char[] chars = new char[1024];
            int len = fileReader.read(chars);
            while (len != -1) {
                len = fileReader.read(chars);
            }
            String currentData = new String(chars);
            System.out.println("读出的数据为:" + currentData);
            //必须手动关闭,因为fileInputStream不属于内存的资源,导致垃圾回收器无法回收这些不用的资源。
            fileReader.close();
        } catch (IOException e) {
            IAssert.throwMsg("写入失败");
        }
    }

    private void outPutStream(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println("创建文件失败:" + path);
            }
        }

        String content = "我是中国人123";
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
        } catch (FileNotFoundException e) {
            IAssert.throwMsg("未找到文件:"+path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException e) {
            IAssert.throwMsg("写入失败");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值