zoukankan      html  css  js  c++  java
  • Java—转换流

    一、转换流

    转换流:OutputStreamWriter & InputStreamReader

    字符转换流原理:字节流+编码表

    二、OutputStreamWriter类

    OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的字符编码表,将要写入流中的字符编码成字节。作用:将字符串按照指定的编码表转成字节,在使用字节流将这些字节写出去

    public class StreamWriter {
    	public static void main(String[] args) throws IOException {
    		writeCN();
    	}
    
    	// 使用转换流:OutputStreamWriter
    	public static void writeCN() throws IOException {
    		// 创建与文件关联的字节输出流对象
    		OutputStream os = new FileOutputStream("e:/text.txt");
    		
    		// 创建可以把字符转成字节的转换流对象,并指定编码
    		Writer writer = new OutputStreamWriter(os, "utf-8");
    		
    		// 调用转换流,把文字写出去,其实是写到了转换流的缓冲区中
    		writer.write("hello你好");
    		
    		writer.close();
    		os.close();
    	}
    }
    

    三、InputStreamReader类

    public class StreamReader {
    	public static void main(String[] args) throws IOException {
    		readCN();
    	}
    
    	public static void readCN() throws IOException {
    		// 创建读取文件的对象
    		InputStream is = new FileInputStream("e:/text.txt");
    		
    		// 创建转换流
    		// 以下创建对象的方法,会用本地默认码表读取,有可能发生错误解码(乱码)
    		// Reader reader = new InputStreamReader(is);
    		Reader reader = new InputStreamReader(is, "utf-8");
    		
    		char[] cbuf = new char[1024 * 8 * 8];
    		int len;
    		while( (len = reader.read(cbuf)) != -1 ){
    			System.out.println(new String(cbuf, 0, len));
    		}
    	
    		reader.close();
    		is.close();
    	}
    }
    

    四、字符流的上下级

    Writer

     |- OutputStreamWriter

      |- FileWriter

    Reader

     |- OutputStreamReader

      |- FileReader

  • 相关阅读:
    Python实现归并排序
    zip解决杨辉三角问题
    Python中协程、多线程、多进程、GIL锁
    Python copy(), deepcopy()
    Python collections的使用
    javascript中的类
    python3中的zip函数
    三数之和(Python and C++解法)
    两数之和(Python and C++解法)
    Python中list、dict、set、tuple的用法细节区别
  • 原文地址:https://www.cnblogs.com/nadou/p/13974072.html
Copyright © 2011-2022 走看看