java之IO操作之 节点流

转换流:字节流转字符流(处理乱码)

二进制(计算机)  解码 字符(人类)

字符(人类) 编码   二进制(计算机)

乱码原因:编码与解码字符集不一致   字节缺少,长度丢失

package learn_java.io.others;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/*
 * 
 * 字节数组节点流
 */
public class ByteArrayDemo01 {
    public static void main(String[] args) throws IOException 
    {    
//        read()    ;
//        write();
        read(write());
    }
        
        /*
         * 
         * 输入流与文件输入流一致
         * 读取字节数组
         */
        
    public  static void read(byte[] src) throws IOException 
    {
//
//        String msg="输入流与文件输入流一致";
//        
//        byte[] src=msg.getBytes();
        
        // 选择流(没有新增方法,可以使用多态)
        
        InputStream is =new BufferedInputStream(
                new ByteArrayInputStream(src));//与外界没有联系,故没有异常,与文件输入流不同
        
        //操作
        byte[] flush =new byte[1024];
        int len=0;
        while(-1!=(len=is. read(flush))) {
            System.out.println(new String(flush,0,len));

        is.close();
        }

        
    }
    
    
    public static byte [] write() throws IOException
    {
        byte[] dest;
        //选择流
        ByteArrayOutputStream bos =new ByteArrayOutputStream();
        //操作写出到bos
        String msg="操作时不能使用多态,因为有新的方法出现了";
        byte[] info =msg.getBytes();
        bos.write(info,0,info.length);
        
        
        //获取数据
        dest=bos.toByteArray();
        bos.close();
        return dest;
    }
}
 

猜你喜欢

转载自blog.csdn.net/qq_38662930/article/details/83999271