Java 8 - Ways to convert an InputStream to String
java 8
12
inputstream
1
Male avatar

loveprogramming viết ngày 04/03/2021

https://grokonez.com/java/ways-to-convert-inputstream-to-string

The tutorial show you many ways to convert an InputStream to String, including using Java 8 Stream.

I. Ways to convert an InputStream to a String
1. Using IOUtils
import org.apache.commons.io.IOUtils;

        String result1 = IOUtils.toString(inputStream, "UTF-8");
2. Using CharStreams
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;

        String result2 = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
3. Using Scanner
import java.util.Scanner;

        Scanner s = null;
        try {
            s = new Scanner(inputStream);
            s.useDelimiter("\\Z");

            String result3 = s.hasNext() ? s.next() : "";
        } finally {
            s.close();
        }
4. Using StringWriter
import java.io.StringWriter;

        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, "UTF-8");
        String result4 = writer.toString();
5. Using ByteArrayOutputStream
import java.io.ByteArrayOutputStream;

        ByteArrayOutputStream bArrOutStrem = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            bArrOutStrem.write(buffer, 0, length);
        }
        String result5 = bArrOutStrem.toString("UTF-8");
6. Using BufferedInputStream
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;

        BufferedInputStream bis = new BufferedInputStream(inputStream);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        int ris = bis.read();
        while (ris != -1) {
            buf.write((byte) ris);
            ris = bis.read();
        }
        String result6 = buf.toString();
7. Using Java 8 Stream
The method: java.io.BufferedReader.lines() returns a Stream.
String result7 = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));
II. Source code
This code is compiled successfully with Java 1.8.
package com.javasampleapproach.instream2string;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Scanner;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;

public class MainApp {

    static String myString = "Java Sample Approach";

    public static void main(String[] args) throws IOException {

        // using IOUtils.toString
        InputStream is = new ByteArrayInputStream(myString.getBytes("UTF-8"));

        String result1 = IOUtils.toString(is, "UTF-8");
        System.out.println("using IOUtils.toString >> " + result1);

        // using CharStreams
        is = new ByteArrayInputStream(myString.getBytes("UTF-8"));

        String result2 = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
        System.out.println("using CharStreams >> " + result2);

        // using Scanner
        is = new ByteArrayInputStream(myString.getBytes("UTF-8"));

        Scanner s = null;
        try {
            s = new Scanner(is);
            s.useDelimiter("\\Z");
            String result3 = s.hasNext() ? s.next() : "";

            System.out.println("using Scanner >> " + result3);
        } finally {
            s.close();
        }

        // using StringWriter
        is = new ByteArrayInputStream(myString.getBytes("UTF-8"));

        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
        String result4 = writer.toString();

        System.out.println("using StringWriter >> " + result4);

        // using ByteArrayOutputStream
        is = new ByteArrayInputStream(myString.getBytes("UTF-8"));

        ByteArrayOutputStream bArrOutStrem = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) != -1) {
            bArrOutStrem.write(buffer, 0, length);
        }
        String result5 = bArrOutStrem.toString("UTF-8");

        System.out.println("using ByteArrayOutputStream >> " + result5);

        // using BufferedInputStream
        is = new ByteArrayInputStream(myString.getBytes("UTF-8"));

        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        int ris = bis.read();
        while (ris != -1) {
            buf.write((byte) ris);
            ris = bis.read();
        }
        String result6 = buf.toString();

        System.out.println("using BufferedInputStream >> " + result6);

        // using Java 8 Stream
        is = new ByteArrayInputStream(myString.getBytes("UTF-8"));
        
        String result7 = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));
        
        System.out.println("using Java 8 Stream >> " + result7);
    }
}
Run code above, the result in console window:
using IOUtils.toString >> Java Sample Approach
using CharStreams >> Java Sample Approach
using Scanner >> Java Sample Approach
using StringWriter >> Java Sample Approach
using ByteArrayOutputStream >> Java Sample Approach
using BufferedInputStream >> Java Sample Approach
using Java 8 Stream >> Java Sample Approach
Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

Male avatar

loveprogramming

444 bài viết.
77 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 6 tháng trước
1 0
Male avatar
1 0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 5 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 5 tháng trước
1 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
444 bài viết.
77 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!