zoukankan      html  css  js  c++  java
  • java 字符转换流

    package cn.sasa.demo4;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    
    public class OutputStreamWriterDemo {
        public static void main(String[] args) throws IOException {
            /**
             * FileWriter 不能指定字符编码
             * 
             * 用OutputStreamWriter
             * 将字符流转成字节流
             *  
             */
    //        writeGBK();
            //writeUTF8();
            //readGBK();
            readUTF8();
        }
        
        static void writeGBK() throws IOException {
            //1、创建一个FileOutputStream,绑定目的
            FileOutputStream output = new FileOutputStream("d:/sasa/test1225.txt");
            
            //2、创建一个OutputStreamWriter,指定字符编码,
            //构造函数的第二个字符串参数指定字符编码,不写默认是系统的默认编码GBK
            OutputStreamWriter writer = new OutputStreamWriter(output);
            
            //3、调用write
            writer.write("你好");
            writer.flush();
            writer.close();
        }
        
        static void writeUTF8() throws IOException {
            FileOutputStream output = new FileOutputStream("d:\sasa\utf.txt");
            OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
            writer.write("啦啦啦");
            writer.flush();
            writer.write("你好");
            writer.flush();
            writer.close();
        }
        
        static void readGBK() throws IOException {
            FileInputStream input = new FileInputStream("d:\sasa\test1225.txt");
            InputStreamReader reader = new InputStreamReader(input);
            char[] charArr = new char[1024];
            @SuppressWarnings("unused")
            int len = 0;
            while((len = reader.read(charArr)) != -1) {
                System.out.print(new String(charArr));
            }
            reader.close();
        }
        
        static void readUTF8() throws IOException {
            FileInputStream input = new FileInputStream("d:\sasa\utf.txt");
            InputStreamReader reader = new InputStreamReader(input , "UTF-8");
            char[] charArr = new char[1024];
            @SuppressWarnings("unused")
            int len = 0;
            while((len = reader.read(charArr)) != -1) {
                System.out.print(new String(charArr));
            }
            reader.close();
        }
    }
  • 相关阅读:
    linux 终端分屏命令vsp(转)
    ACE消息队列(转)
    iovec结构体定义及使用 (转)
    转: 写给想成为前端工程师的同学们 (from 360前端团队)
    转:苹果企业级开发者账号申请流程
    奇舞团的博客(360前端团队)
    腾讯开源组件
    转:android studio入门合集
    Raid分类说明 (from mongodb权威指南)
    转: linux下的自动对时
  • 原文地址:https://www.cnblogs.com/SasaL/p/10173316.html
Copyright © 2011-2022 走看看