java-IO流5(输入字符流)

来源:互联网 发布:office word 2016 mac 编辑:程序博客网 时间:2024/05/22 08:02

介绍输入字符流之前先看下面案例:

注意:

何时使用字符流,何时使用字节流?依据是什么?

使用字符流的应用场景: 如果是读写字符数据的时候则使用字符流。

使用字节流的应用场景: 如果读写的数据都不需要转换成字符的时候,则使用字节流。

使用字节流读写中文案例:(比较麻烦)

public class Demo1 {    public static void main(String[] args) throws IOException {//      writeTest();        readrTest();    }    //使用字节流读取中文    public static void readrTest() throws IOException{        //找到目标文件        File file = new File("F:\\a.txt");        //建立数据的输入通道        FileInputStream fileInputStream = new FileInputStream(file);        //读取内容        //int content = 0;        /*while((content = fileInputStream.read())!=-1){ //出现乱码的原因: 一个中文在gbk码表中默认是占两个字节,                                                       // 目前你只读取了一个字节而已,所以不是一个完整的中文。            System.out.print((char)content);        }*/        byte[] buf = new byte[2];        for(int i = 0 ; i < 3 ; i++){            fileInputStream.read(buf);            System.out.print(new String(buf));        }        //关闭资源        fileInputStream.close();    }    //使用字节流写中文。   字节流之所以能够写中文是因为借助了字符串的getBytes方法对字符串进行了编码(字符---->数字)。     public static void writeTest() throws IOException{        //找到目标文件        File file = new File("F:\\a.txt");        //建立数据的输出通道        FileOutputStream fileOutputStream  = new FileOutputStream(file);        //准备数据,把数据写出。        String data = "大家好";        byte[] buf = data.getBytes();   //把字符串转换成字节数组        System.out.println("输出的内容:"+ Arrays.toString(buf));        fileOutputStream.write(buf);        ///关闭资源        fileOutputStream.close();    }}

字节流:字节流读取的是文件中的二进制数据,读到的数据并不会帮你转换成你看得懂的字符。

字符流: 字符流会把读取到的二进制的数据进行对应 的编码与解码工作。

字符流 = 字节流 + 编码(解码)

输入字符流:

———-| Reader 输入字符流的基类 (抽象类)
————-| FileReader 读取文件的输入字符流。

FileReader的用法:

1. 找到目标文件2. 建立数据的输入通道3. 读取数据4. 关闭资源
public class Demo2 {    public static void main(String[] args) throws IOException {        readTest2();    }    //使用缓冲字符数组读取文件。    public static void readTest2() throws IOException{        //找到目标文件        File file = new File("F:\\1208project\\day21\\src\\day21\\Demo1.java");        // 建立数据的输入通道        FileReader fileReader = new FileReader(file);        //建立缓冲字符数组读取文件数据        char[] buf = new char[1024];        int length = 0 ;         while((length = fileReader.read(buf))!=-1){            System.out.print(new String(buf,0,length));        }    }    public static void readTest1() throws IOException{        //找到目标文件        File file = new File("F:\\1208project\\day21\\src\\day21\\Demo1.java");        //建立数据的输入通道        FileReader fileReader = new FileReader(file);        int content = 0 ;        while((content = fileReader.read())!=-1){ //每次只会读取一个字符,效率低。            System.out.print((char)content);        }        //关闭资源        fileReader.close();    }}
0 0
原创粉丝点击