java基础之输入流转换

1.输入流转字节

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

public class stream2Byte {
    public static byte[] getStream2Byte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(buf)) != -1) {
          outStream.write(buf, 0, len);
        }
        return outStream.toByteArray();
    }
}

2.输入流转字符串

import java.io.IOException;
import java.io.InputStream;

public class stream2Str {
    public static String getStream2Str(InputStream inputStream) {
        StringBuffer sb = new StringBuffer();
        byte[] buf = new byte[1024];
        int len = -1;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "utf-8"));
            }
        } catch (IOException e) {
            return null;
        }
        return sb.toString();
    }
}

3.网络流转字符串

public static String getStrByUrlConnection(String spec) {
        String result = null;
        try {
            URL url = new URL(spec);
            URLConnection urlConnection = url.openConnection();//打开一个网络流
            /* send get request default */
            urlConnection.setDoInput(true);
            /* send post request, communication through url.getOutputStream */
            // urlConnection.setDoOutput(true);
            // OutputStream outputStream = urlConnection.getOutputStream();
            InputStream inputStream = urlConnection.getInputStream();
            result = stream2Str.getStream2Str(inputStream);
        } catch (IOException e) {
            return null;
        }
        return result;
    }

 

你可能感兴趣的:(java基础)