Java字符流的读写操作

字符流是可以读取文字,而字节流不能(读文字的话会出现乱码)

字符流:是以Reader Writer结尾的

字节流:inputStream outputStream

public class bbbb {
    public static void main(String[] args) {
        File file=new File("D:/a/1.txt");
        FileReader fr=null;
        try {
            fr=new FileReader(file);
            int index=0;
            while ((index= fr.read())!=-1){
                System.out.println((char) index);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

写入

System.out.println("=========写入操作FileWriter===========");
        File file=new File("D:/a/1.txt");
        FileWriter fw=null;
        try {
            fw=new FileWriter(file,true);
            String bb="不会";
            fw.write(bb);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fw.close();//记得关流
            } catch (IOException e) {
                e.printStackTrace();
            }

读写操作相当于把文件的内容复制到另一个新建文件中

  System.out.println("===========读写操作============");
        File file1=new File("D:/a/1.txt");
        File file2=new File("D:/a/3.txt");
        FileReader fr=null;
        FileWriter fw=null;
        try {
            fr=new FileReader(file1);
            fw=new FileWriter(file2);
            char[]c=new char[(int)file1.length()];
            int read=fr.read(c);
            String res=new String(c,0,read);
            System.out.println(res);
            fw.write(res);
            /*char[] c = new char[(int)file1.length()];
            System.out.println("实际获得的数组的长度是:"+c.length);
            int read = fr.read(c);
            System.out.println("实际包含的字符数量为:"+read);
            //为了处理多余字符 创建字符串时 进行处理
            String res = new String(c,0,read);
            System.out.println(res);
            fw.write(res);*/

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fr.close();
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值