InputSteam转String

1、使用 InputStreamReader 和 StringBuilder (JDK)

public class InputStream2String {
    public static void main(String[] args) {
        try {
            InputStream inputStream = new FileInputStream("E:/duckAndJava/IO/testFile.txt");    //路径修改为本地文件所在的位置

            char[] buffer = new char[1024];    //根据需要的数组大小进行自定义
            StringBuilder out = new StringBuilder();
            Reader in = new InputStreamReader(inputStream, "UTF-8");
            for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
                out.append(buffer, 0, numRead);
            }
            String myString =  out.toString();

            System.out.println("myString = " + myString);

        }catch (IOException e){
            e.printStackTrace();
        }
    }

2、使用 inputStream.read() and StringBuilder

StringBuilder sb = new StringBuilder();for (int ch; (ch = inputStream.read()) != -1; ) {    sb.append((char) ch);}String myString = sb.toString();

3、使用 ByteArrayOutputStream and inputStream.read

ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; for (int length; (length = inputStream.read(buffer)) != -1; ) {     result.write(buffer, 0, length); } String myString = result.toString("UTF-8");

4、使用 BufferedInputStream 和 ByteArrayOutputStream

BufferedInputStream bis = new BufferedInputStream(inputStream);ByteArrayOutputStream buf = new ByteArrayOutputStream();for (int result = bis.read(); result != -1; result = bis.read()) {    buf.write((byte) result);}String myString = buf.toString("UTF-8");

5、使用 BufferedReader

String newLine = System.getProperty("line.separator"); BufferedReader reader = new BufferedReader(         new InputStreamReader(inputStream)); StringBuilder result = new StringBuilder(); for (String line; (line = reader.readLine()) != null; ) {     if (result.length() > 0) {         result.append(newLine);     }     result.append(line); } String myString = result.toString();

6、使用 Stream API 或 parallel Stream API

String myString = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));

 String myString = new BufferedReader(new InputStreamReader(inputStream)).lines().parallel().collect(Collectors.joining("\n"));

7、使用 StringWriter 和IOUtils.copy (Apache Commons)

StringWriter writer = new StringWriter();IOUtils.copy(inputStream, writer, "UTF-8");return writer.toString();

甚至可以直接这样用

String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

8、使用CharStreams (Google Guava)

String result = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值