转换流和标准输入和输出流

转换流提供了字符流和字节流之间的转换

InputStreamReader和OutputStreamWriter

字节流中的数据都是字符时,转成字符流操作更高效

/*
转换流:inputStreamReader OutputStreamWriter
编码:字符串  ---> 字节数组
       字节数组 ---> 字符串
 */
@Test
public void test1(){
    //解码
    BufferedReader br =null;
    BufferedWriter bw = null;
    try {
        File file = new File("a.txt");
        FileInputStream  fis  = new FileInputStream(file);
        InputStreamReader  isr  = new InputStreamReader(fis, "GBK");
        br = new BufferedReader(isr);

        //编码
        File file2 = new File("a5.txt");
        FileOutputStream fos = new FileOutputStream(file2);
        OutputStreamWriter osw = new OutputStreamWriter(fos);

        bw = new BufferedWriter(osw);
        String str;
        while ((str = br.readLine())!=null){
            bw.write(str);
            bw.newLine();
            bw.flush();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (bw != null){
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (br!= null){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}

标准输入输出流

/*
标准的输入输出流
题目:从键盘中输入字符串,要求读取到整行字符串转换成大写输出
直到输入"e"或"exit"时,退出程序
 */
@Test
public void test2(){
    BufferedReader br = null;
    try {
        InputStream is = System.in;
        InputStreamReader isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String str ;
        while (true){
            System.out.println("请输入字符串:");
            str = br.readLine();
            if (str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")){
                break;
            }
            String str1 = str.toUpperCase();
            System.out.println(str1);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (br!=null){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

编码表的由来

计算机只能识别二进制数据,早期由来是电信号。为了方便应用计算机,让它可以识别各个国家的文字。就将各个国家的文字用数字来表示,并一一对应,形成一张表。这就是编码表。
编码表的由来
计算机只能识别二进制数据,早期由来是电信号。为了方便应用计算机,让它可以识别各个国家的文字。就将各个国家的文字用数字来表示,并一一对应,形成一张表。这就是编码表。

常见的编码表

ASCII:美国标准信息交换码。
用一个字节的7位可以表示。
ISO8859-1:拉丁码表。欧洲码表
用一个字节的8位表示。
GB2312:中国的中文编码表。
GBK:中国的中文编码表升级,融合了更多的中文文字符号。
Unicode:国际标准码,融合了多种文字。
所有文字都用两个字节来表示,Java语言使用的就是unicode
UTF-8:最多用三个字节来表示一个字符。

猜你喜欢

转载自blog.csdn.net/wwwzydcom/article/details/85052460