Как преобразовать InputStream в String в Java
В Java есть несколько способов преобразоватьInputStream
вString
:
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 -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 в String
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(); } }