zoukankan      html  css  js  c++  java
  • Java学习笔记39(转换流)

    转换流:字符流和字节流之间的桥梁

    用于处理程序的编码问题

    OutputStreamWriter类:字符转字节流

    写文本文件:

    package demo;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    
    public class Demo {
        public static void main(String[] args) throws IOException {
            writeGBK();
            writeUTF8();
        }
    
        public static void writeGBK() throws IOException {
            FileOutputStream fos = new FileOutputStream("d:\gbk.txt");
            OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
            osw.write("你好");// gbk的一个汉字是2个字节
            osw.close();
        }
    
        public static void writeUTF8() throws IOException {
            FileOutputStream fos = new FileOutputStream("d:\utf8.txt");
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write("你好");// utf8的一个汉字是3个字节
            osw.close();
        }
    }

    InputStreamReader类:

    字节转字符流过程:

    这里读取上面写的文本文件:

    package demo;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class Demo {
        public static void main(String[] args) throws IOException {
            readGBK();
            readUTF8();
        }
    
        public static void readGBK() throws IOException {
            FileInputStream fis = new FileInputStream("d:\gbk.txt");
            InputStreamReader isr = new InputStreamReader(fis);
            char[] ch = new char[1024];
            int len = isr.read(ch);
            System.out.println(new String(ch, 0, len));
        }
    
        public static void readUTF8() throws IOException {
            FileInputStream fis = new FileInputStream("d:\utf8.txt");
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            char[] ch = new char[1024];
            int len = isr.read(ch);
            System.out.println(new String(ch, 0, len));
        }
    }

    这里注意,如果编码集和读取问文本不一致,就会发生乱码或者输出?的问题

  • 相关阅读:
    this与$(this)的区别
    用CSS3实现文字渐变效果
    css3,filter实现背景背景渐变的效果
    jQuery DOM 元素方法 index() 方法
    toggleClass() 隐藏层
    AJAX与WebService
    对于JSP台头的理解,和预设的重要性
    [转]windows下修改eclipse的默认编码+[转]eclipse 默认文件编码修改
    使用Meta自动定时刷新页面及一些HTML标记
    后台代码里执行弹出脚本方法!(Response.Write)(转)
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8290553.html
Copyright © 2011-2022 走看看