JavaでInputStreamをStringに変換する方法

JavaでStringにInputStreamを変換する方法

Javaでは、InputStreamStringに変換する方法はいくつかあります。

1. 純粋なJava –ByteArrayOutputStream

    private static String convertInputStreamToString(InputStream inputStream)
        throws IOException {

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(StandardCharsets.UTF_8.name());

    }

2. Java 9の場合は、次のinputStream.readAllBytesを試してください。

    private static String convertInputStreamToStringJDK9(InputStream inputStream)
        throws IOException {

        return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);

    }

3. Apache Commons IO –IOUtils.copy

pom.xml

    
        commons-io
        commons-io
        2.6
    
    private static String convertInputStreamToStringCommonIO(InputStream inputStream)
        throws IOException {

        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);
        return writer.toString();

    }

1. InputStreamを文字列に変換

InputStreamToString.java

package com.example;

import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.nio.charset.StandardCharsets;

public class InputStreamToString {

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

        URI u = URI.create("https://www.google.com/");
        try (InputStream inputStream = u.toURL().openStream()) {

            // InputStream -> String
            String result = convertInputStreamToString(inputStream);
            System.out.println(result);

        }

    }

    // Pure Java
    private static String convertInputStreamToString(InputStream inputStream) throws IOException {

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        return result.toString(StandardCharsets.UTF_8.name());

    }

    // Since Java 9
    private static String convertInputStreamToStringJDK9(InputStream inputStream) throws IOException {
        return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
    }

    // commons-io
    private static String convertInputStreamToStringCommonIO(InputStream inputStream) throws IOException {
        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);
        return writer.toString();
    }

}