java基础语法(二十九)FileReader和FileWriter的使用

1、FileReader

文件字符输入流,只能读取普通文本。
读取文本内容时,比较方便,快捷。

public class FileReaderTest {
    public static void main(String[] args) {
        FileReader reader=null;
        try {
            //创建文件字符输入流
            reader = new FileReader("temp.txt");

            //创建一个char数组
            char[] chars=new char[4];
            //往char数组中读
            reader.read(chars);
            for (char c:chars){
                System.out.println(c);
            }
            /*//开始读
            char[] chars=new char[4];//一次读取4个字符
            int readcount=0;
            while ((readcount=reader.read(chars))!=-1){
                System.out.print(new String(chars,0,readcount));
            }

             */

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2、 FileWriter

文件字符输出流。写
只能输出普通文本。

public class FileWriterTest {
    public static void main(String[] args) {
        FileWriter out = null;
        try {
            //创建文件字符输出流对象
            //out = new FileWriter("file");
            //以上方式,每执行一次,第二次执行时,清空内容重新写入
            //以下方式,不清空内容,末尾追加
            out = new FileWriter("file",true);
            //开始写
            char[] chars={'今','天','吃','了','饺','子'};
            out.write(chars);
            out.write(chars,2,4);
            out.write("\n");
            out.write("下午又要上课");


            //刷新
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值