字符型文件输入流、字符型文件输出流

本文主要内容:

(1)字符型文件输入流
(2)字符型文件输出流

1.读取中文可能会产生问题,例子如下:

public class Test4 {
    public static void main(String[] args) {
        //字节输入流,读取中文可能会产生问题
        //字节流的好处在于什么类型的文件都可以处理,不好在于处理纯文本的文件
        //可能会产生乱码的问题
        try {
            FileInputStream fis = new FileInputStream(new File("D://test//Test.txt"));
            byte[] b = new byte[5];
            int count = fis.read(b);
            while (count!=-1){
                String s = new String(b,0,count);
                System.out.println(s);
                count = fis.read(b);
            }
            System.out.println("打印完毕");
            //我�
            //�欢�
            //��abc
            //打印完毕
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.字符型文件输入流(FileReader)
(1)java.io包
(2)继承于InputStreamReader、Reader
(3)构造方法:带file的构造方法
(4)常用方法:
read();read(char[]);close();

public class Test5 {
    public static void main(String[] args) {
        FileReader fr = null;
        try {
            File file = new File("D://test//Test.txt");
            fr = new FileReader(file);
            int code = fr.read();
            while (code!=-1){
                System.out.println((char)code);
                code = fr.read();
            }
            System.out.println("完毕");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fr!=null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3.字符型文件输出流(FileWriter)
(1)java.io包
(2)继承于OutPutStreamWriter、Writer
(3)构造方法:带file参数、带file、boolean参数、带String参数、带String、boolean参数
(4)常用方法:
write(int);write(char[]);write(String);flush();close();

public class Test6 {
    public static void main(String[] args) {
        FileWriter fw = null;
        try {
            File file = new File("D://test//Test.txt");
            fw = new FileWriter(file);
            char[] ch = {'我','喜','欢','你'};
            fw.write(ch);
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值