InputStream转换为String, byte[] data = new byte[1024]详解

import java.io.*;
import java.nio.charset.Charset;

public class Main {

    public static void main(String[] args) {
        String str = "hello123456";
        String str2 = "";
        try {
            InputStream inputStream = new ByteArrayInputStream(str.getBytes("UTF-8")); ///这里需要用try...catch...不然报错
//            ByteArrayInputStream:ByteArrayInputStream(byte[] buf)
//            创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组。
//            String:byte[] getBytes(Charset charset)
//            使用给定的 charset 将此 String 编码到 byte 序列,并将结果存储到新的 byte 数组。
            str2 = changeInputStream(inputStream, "utf-8");
            System.out.println(str2);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }//main

    public static String changeInputStream(InputStream inputStream, String encode) {
        String res = "";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
       // byte[] data = new byte[100];///输出 hello123456
        byte[] data = new byte[5];///输出 hello123456
        int len = 0;
        try {
            while ((len = inputStream.read(data)) != -1) { ////inputStream-->data[]
//               InputStream: int read(byte[] b)
//                从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
//                返回:
//                读入缓冲区的总字节数;如果因为已经到达流末尾而不再有数据可用,则返回 -1。

                outputStream.write(data, 0, len);/////outputStream<--data[]
//              ByteArrayOutputStream:  void write(byte[] b, int off, int len)
//                将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte 数组输出流。
            }
            res = new String(outputStream.toByteArray(), encode);
//          ByteArrayOutputStream:  byte[] toByteArray()
//            创建一个新分配的 byte 数组。
//          String:  String(byte[] bytes, Charset charset)
//            通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。

            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }//changeInputStream
}
我最想说明的是,虽然data[]的长度比string短,但仍然也会输出string的所有字符,不会只输出data[]的长度的字符串
第一次取前5个字符写入outputStream中,往后都是每次写入5个字符到outputStream中,直到写入到字符串末尾
见单步调试过程
 
  

InputStream转换为String, byte[] data = new byte[1024]详解_第1张图片

另外这是我个人开发的App,欢迎下载和好评,V1.5.0版本正在努力开发中......

http://www.wandoujia.com/apps/com.example.viewpager_3





你可能感兴趣的:(Java)