¿Cómo leo / convierto un InputStream en un String en Java?
Frecuentes
Visto 2,229 equipos
4267
Si usted tiene una java.io.InputStream
objeto, ¿cómo debería procesar ese objeto y producir un String
?
Supongamos que tengo un InputStream
que contiene datos de texto y quiero convertirlo en un String
, por ejemplo, puedo escribir eso en un archivo de registro.
¿Cuál es la forma más fácil de tomar el InputStream
y convertirlo en un String
?
public String convertStreamToString(InputStream is) {
// ???
}
30 Respuestas
2651
Una buena forma de hacer esto es usar bienes comunes Apache IOUtils
para copiar el InputStream
post-extracción StringWriter
... algo como
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
o incluso
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
Alternativamente, podrías usar ByteArrayOutputStream
si no quieres mezclar tus Streams y Writers
contestado el 21 de mayo de 18 a las 14:05
¿El toString quedó obsoleto? veo IOUtils.convertStreamToString()
- RCB
2774
Resumir otras respuestas Encontré 11 formas principales de hacer esto (ver más abajo). Y escribí algunas pruebas de rendimiento (vea los resultados a continuación):
Formas de convertir un InputStream en un String:
Usar
IOUtils.toString
(Utilidades de Apache)String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
Usar
CharStreams
(Guayaba)String result = CharStreams.toString(new InputStreamReader( inputStream, Charsets.UTF_8));
Usar
Scanner
(JDK)Scanner s = new Scanner(inputStream).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : "";
Usar API de transmisión (Java 8). advertencia: Esta solución convierte diferentes saltos de línea (como
\r\n
) A\n
.String result = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining("\n"));
Usar API de transmisión paralela (Java 8). advertencia: Esta solución convierte diferentes saltos de línea (como
\r\n
) A\n
.String result = new BufferedReader(new InputStreamReader(inputStream)) .lines().parallel().collect(Collectors.joining("\n"));
Usar
InputStreamReader
eStringBuilder
(JDK)int bufferSize = 1024; char[] buffer = new char[bufferSize]; StringBuilder out = new StringBuilder(); Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8); for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) { out.append(buffer, 0, numRead); } return out.toString();
Usar
StringWriter
eIOUtils.copy
(Apache común)StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); return writer.toString();
Usar
ByteArrayOutputStream
einputStream.read
(JDK)ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; for (int length; (length = inputStream.read(buffer)) != -1; ) { result.write(buffer, 0, length); } // StandardCharsets.UTF_8.name() > JDK 7 return result.toString("UTF-8");
Usar
BufferedReader
(JDK). Aviso: Esta solución convierte diferentes saltos de línea (como\n\r
) Aline.separator
propiedad del sistema (por ejemplo, en Windows a "\ r \ n").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); } return result.toString();
Usar
BufferedInputStream
eByteArrayOutputStream
(JDK)BufferedInputStream bis = new BufferedInputStream(inputStream); ByteArrayOutputStream buf = new ByteArrayOutputStream(); for (int result = bis.read(); result != -1; result = bis.read()) { buf.write((byte) result); } // StandardCharsets.UTF_8.name() > JDK 7 return buf.toString("UTF-8");
Usar
inputStream.read()
eStringBuilder
(JDK). advertencia: Esta solución tiene problemas con Unicode, por ejemplo, con texto en ruso (funciona correctamente solo con texto que no es Unicode)StringBuilder sb = new StringBuilder(); for (int ch; (ch = inputStream.read()) != -1; ) { sb.append((char) ch); } return sb.toString();
advertencia:
Las soluciones 4, 5 y 9 convierten diferentes saltos de línea en uno.
La solución 11 no puede funcionar correctamente con texto Unicode
Pruebas de rendimiento
Pruebas de rendimiento para pequeños String
(longitud = 175), URL en gitHub (modo = tiempo promedio, sistema = Linux, la puntuación 1,343 es la mejor):
Benchmark Mode Cnt Score Error Units
8. ByteArrayOutputStream and read (JDK) avgt 10 1,343 ± 0,028 us/op
6. InputStreamReader and StringBuilder (JDK) avgt 10 6,980 ± 0,404 us/op
10. BufferedInputStream, ByteArrayOutputStream avgt 10 7,437 ± 0,735 us/op
11. InputStream.read() and StringBuilder (JDK) avgt 10 8,977 ± 0,328 us/op
7. StringWriter and IOUtils.copy (Apache) avgt 10 10,613 ± 0,599 us/op
1. IOUtils.toString (Apache Utils) avgt 10 10,605 ± 0,527 us/op
3. Scanner (JDK) avgt 10 12,083 ± 0,293 us/op
2. CharStreams (guava) avgt 10 12,999 ± 0,514 us/op
4. Stream Api (Java 8) avgt 10 15,811 ± 0,605 us/op
9. BufferedReader (JDK) avgt 10 16,038 ± 0,711 us/op
5. parallel Stream Api (Java 8) avgt 10 21,544 ± 0,583 us/op
Pruebas de rendimiento para grandes String
(longitud = 50100), URL en gitHub (modo = tiempo promedio, sistema = Linux, la puntuación 200,715 es la mejor):
Benchmark Mode Cnt Score Error Units
8. ByteArrayOutputStream and read (JDK) avgt 10 200,715 ± 18,103 us/op
1. IOUtils.toString (Apache Utils) avgt 10 300,019 ± 8,751 us/op
6. InputStreamReader and StringBuilder (JDK) avgt 10 347,616 ± 130,348 us/op
7. StringWriter and IOUtils.copy (Apache) avgt 10 352,791 ± 105,337 us/op
2. CharStreams (guava) avgt 10 420,137 ± 59,877 us/op
9. BufferedReader (JDK) avgt 10 632,028 ± 17,002 us/op
5. parallel Stream Api (Java 8) avgt 10 662,999 ± 46,199 us/op
4. Stream Api (Java 8) avgt 10 701,269 ± 82,296 us/op
10. BufferedInputStream, ByteArrayOutputStream avgt 10 740,837 ± 5,613 us/op
3. Scanner (JDK) avgt 10 751,417 ± 62,026 us/op
11. InputStream.read() and StringBuilder (JDK) avgt 10 2919,350 ± 1101,942 us/op
Gráficos (pruebas de rendimiento según la longitud del flujo de entrada en el sistema Windows 7)
Prueba de rendimiento (tiempo promedio) según la longitud del flujo de entrada en el sistema Windows 7:
length 182 546 1092 3276 9828 29484 58968
test8 0.38 0.938 1.868 4.448 13.412 36.459 72.708
test4 2.362 3.609 5.573 12.769 40.74 81.415 159.864
test5 3.881 5.075 6.904 14.123 50.258 129.937 166.162
test9 2.237 3.493 5.422 11.977 45.98 89.336 177.39
test6 1.261 2.12 4.38 10.698 31.821 86.106 186.636
test7 1.601 2.391 3.646 8.367 38.196 110.221 211.016
test1 1.529 2.381 3.527 8.411 40.551 105.16 212.573
test3 3.035 3.934 8.606 20.858 61.571 118.744 235.428
test2 3.136 6.238 10.508 33.48 43.532 118.044 239.481
test10 1.593 4.736 7.527 20.557 59.856 162.907 323.147
test11 3.913 11.506 23.26 68.644 207.591 600.444 1211.545
Respondido 28 Feb 21, 02:02
Buen trabajo. Podría ser útil proporcionar un resumen tl; dr en la parte inferior, es decir, descartar las soluciones que tienen problemas con los saltos de línea / unicode y luego (de las que quedan) decir cuál es la más rápida con o sin bibliotecas externas. - Steve Cámaras
¿Qué es el reset (); para en 11? - paula livingstone
Parece que esta respuesta está incompleta. gigino
Necesito marcar esta respuesta, vengo aquí con demasiada frecuencia. barke
Convertí todos los while
bucles a for
realiza un bucle en una edición de esta publicación, para evitar contaminar el espacio de nombres con una variable que no se usa fuera del bucle. Es un buen truco que funciona en la mayoría de los bucles de lectura / escritura de Java. - Lucas Hutchison
2327
Aquí hay una forma de usar solo la biblioteca estándar de Java (tenga en cuenta que la transmisión no está cerrada, su kilometraje puede variar).
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
Aprendí este truco de "Trucos estúpidos del escáner" artículo. La razón por la que funciona es porque Escáners itera sobre los tokens en el flujo, y en este caso separamos los tokens usando "comienzo del límite de entrada" (\ A), lo que nos da solo un token para todo el contenido del flujo.
Tenga en cuenta que si necesita ser específico sobre la codificación del flujo de entrada, puede proporcionar el segundo argumento para Scanner
constructor que indica qué juego de caracteres utilizar (por ejemplo, "UTF-8").
La punta del sombrero también va a Jacob, quien una vez me señaló dicho artículo.
Respondido el 05 de enero de 19 a las 10:01
¿No deberíamos cerrar el escáner antes de devolver el valor? - Oleg Markélov
@OlegMarkelov probablemente. - Pavel Repin
863
Apache Commons permite:
String myString = IOUtils.toString(myInputStream, "UTF-8");
Por supuesto, puede elegir otras codificaciones de caracteres además de UTF-8.
Ver también: (documentación)
Respondido el 05 de enero de 19 a las 10:01
Intentando recuperar InputStream, no funciona stackoverflow.com/q/66349701/3425489 - Shantaram tupé
306
Teniendo en cuenta el archivo uno primero debe obtener un java.io.Reader
ejemplo. Esto luego se puede leer y agregar a un StringBuilder
(no necesitamos StringBuffer
si no estamos accediendo a él en varios subprocesos, y StringBuilder
es más rápido). El truco aquí es que trabajamos en bloques y, como tal, no necesitamos otros flujos de almacenamiento en búfer. El tamaño del bloque está parametrizado para optimizar el rendimiento en tiempo de ejecución.
public static String slurp(final InputStream is, final int bufferSize) {
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try (Reader in = new InputStreamReader(is, "UTF-8")) {
for (;;) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
}
catch (UnsupportedEncodingException ex) {
/* ... */
}
catch (IOException ex) {
/* ... */
}
return out.toString();
}
Respondido 15 Jul 15, 11:07
257
Uso:
InputStream in = /* Your InputStream */;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;
while ((read=br.readLine()) != null) {
//System.out.println(read);
sb.append(read);
}
br.close();
return sb.toString();
Respondido el 05 de enero de 19 a las 10:01
175
Si está utilizando Google-Collections / Guava, puede hacer lo siguiente:
InputStream stream = ...
String content = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
Closeables.closeQuietly(stream);
Tenga en cuenta que el segundo parámetro (es decir, Charsets.UTF_8) para el InputStreamReader
no es necesario, pero generalmente es una buena idea especificar la codificación si la conoce (¡lo cual debería!)
Respondido el 30 de enero de 13 a las 16:01
127
Esta es la mejor solución Java pura que se adapta perfectamente a Android y cualquier otra JVM.
Esta solución funciona increíblemente bien ... ¡es simple, rápida y funciona de la misma manera en flujos pequeños y grandes! (ver el punto de referencia arriba ... No. 8)
public String readFullyAsString(InputStream inputStream, String encoding)
throws IOException {
return readFully(inputStream).toString(encoding);
}
public byte[] readFullyAsBytes(InputStream inputStream)
throws IOException {
return readFully(inputStream).toByteArray();
}
private ByteArrayOutputStream readFully(InputStream inputStream)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos;
}
Respondido 23 Jul 19, 21:07
112
Para completar, aquí está Java 9 solución:
public static String toString(InputStream input) throws IOException {
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
Esto usa el readAllBytes
método que se agregó a Java 9.
respondido 18 nov., 20:22
70
Uso:
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
public static String readInputStreamAsString(InputStream in)
throws IOException {
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
byte b = (byte)result;
buf.write(b);
result = bis.read();
}
return buf.toString();
}
Respondido el 05 de enero de 19 a las 10:01
66
Aquí está la solución más elegante, pura-Java (sin biblioteca) que se me ocurrió después de un poco de experimentación:
public static String fromStream(InputStream in) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}
Respondido el 07 de diciembre de 13 a las 16:12
57
Hice un punto de referencia sobre 14 respuestas distintas aquí (lo siento por no proporcionar créditos, pero hay demasiados duplicados).
El resultado es muy sorprendente. Resulta que Apache IOUtils es el mas lento y ByteArrayOutputStream
son las soluciones más rápidas:
Entonces, primero aquí está el mejor método:
public String inputStreamToString(InputStream inputStream) throws IOException {
try(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(UTF_8);
}
}
Resultados de referencia, de 20 MB de bytes aleatorios en 20 ciclos
Tiempo en milisegundos
- ByteArrayOutputStreamPrueba: 194
- Nio Corriente: 198
- Java9ISTransferir a: 201
- Java9ISReadAllBytes: 205
- BufferedInputStreamVsByteArrayOutputStream: 314
- ApacheStringWriter2: 574
- GuavaChar Corrientes: 589
- Escáner Lector No Siguiente Prueba: 614
- Lector de escáner: 633
- ApacheString Writer: 1544
- StreamApi: error
- ParallelStreamApi: Error
- Prueba de lectura de búfer: error
- InputStreamAndStringBuilder: Error
Código fuente de referencia
import com.google.common.io.CharStreams;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
/**
* Created by Ilya Gazman on 2/13/18.
*/
public class InputStreamToString {
private static final String UTF_8 = "UTF-8";
public static void main(String... args) {
log("App started");
byte[] bytes = new byte[1024 * 1024];
new Random().nextBytes(bytes);
log("Stream is ready\n");
try {
test(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void test(byte[] bytes) throws IOException {
List<Stringify> tests = Arrays.asList(
new ApacheStringWriter(),
new ApacheStringWriter2(),
new NioStream(),
new ScannerReader(),
new ScannerReaderNoNextTest(),
new GuavaCharStreams(),
new StreamApi(),
new ParallelStreamApi(),
new ByteArrayOutputStreamTest(),
new BufferReaderTest(),
new BufferedInputStreamVsByteArrayOutputStream(),
new InputStreamAndStringBuilder(),
new Java9ISTransferTo(),
new Java9ISReadAllBytes()
);
String solution = new String(bytes, "UTF-8");
for (Stringify test : tests) {
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
String s = test.inputStreamToString(inputStream);
if (!s.equals(solution)) {
log(test.name() + ": Error");
continue;
}
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < 20; i++) {
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
test.inputStreamToString(inputStream);
}
}
log(test.name() + ": " + (System.currentTimeMillis() - startTime));
}
}
private static void log(String message) {
System.out.println(message);
}
interface Stringify {
String inputStreamToString(InputStream inputStream) throws IOException;
default String name() {
return this.getClass().getSimpleName();
}
}
static class ApacheStringWriter implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, UTF_8);
return writer.toString();
}
}
static class ApacheStringWriter2 implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
return IOUtils.toString(inputStream, UTF_8);
}
}
static class NioStream implements Stringify {
@Override
public String inputStreamToString(InputStream in) throws IOException {
ReadableByteChannel channel = Channels.newChannel(in);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 16);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
WritableByteChannel outChannel = Channels.newChannel(bout);
while (channel.read(byteBuffer) > 0 || byteBuffer.position() > 0) {
byteBuffer.flip(); //make buffer ready for write
outChannel.write(byteBuffer);
byteBuffer.compact(); //make buffer ready for reading
}
channel.close();
outChannel.close();
return bout.toString(UTF_8);
}
}
static class ScannerReader implements Stringify {
@Override
public String inputStreamToString(InputStream is) throws IOException {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
static class ScannerReaderNoNextTest implements Stringify {
@Override
public String inputStreamToString(InputStream is) throws IOException {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.next();
}
}
static class GuavaCharStreams implements Stringify {
@Override
public String inputStreamToString(InputStream is) throws IOException {
return CharStreams.toString(new InputStreamReader(
is, UTF_8));
}
}
static class StreamApi implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
return new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining("\n"));
}
}
static class ParallelStreamApi implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
return new BufferedReader(new InputStreamReader(inputStream)).lines()
.parallel().collect(Collectors.joining("\n"));
}
}
static class ByteArrayOutputStreamTest implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
try(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(UTF_8);
}
}
}
static class BufferReaderTest implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
String newLine = System.getProperty("line.separator");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder(UTF_8);
String line;
boolean flag = false;
while ((line = reader.readLine()) != null) {
result.append(flag ? newLine : "").append(line);
flag = true;
}
return result.toString();
}
}
static class BufferedInputStreamVsByteArrayOutputStream implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while (result != -1) {
buf.write((byte) result);
result = bis.read();
}
return buf.toString(UTF_8);
}
}
static class InputStreamAndStringBuilder implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
int ch;
StringBuilder sb = new StringBuilder(UTF_8);
while ((ch = inputStream.read()) != -1)
sb.append((char) ch);
return sb.toString();
}
}
static class Java9ISTransferTo implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
inputStream.transferTo(bos);
return bos.toString(UTF_8);
}
}
static class Java9ISReadAllBytes implements Stringify {
@Override
public String inputStreamToString(InputStream inputStream) throws IOException {
return new String(inputStream.readAllBytes(), UTF_8);
}
}
}
Respondido el 06 de enero de 19 a las 00:01
Hacer evaluaciones comparativas en Java no es fácil (especialmente debido a JIT). Después de leer el código fuente de Benchmark, estoy convencido de que esos valores anteriores no son precisos y todos deben tener cuidado al creerlos. - Dalibor
@Dalibor, probablemente debería proporcionar más razonamientos para su reclamo en lugar de solo un enlace. - Ilya Gazmán
Creo que es un hecho realmente conocido que no es fácil hacer su propio punto de referencia. Para los que no lo sepan, hay un enlace;) - Dalibor
@Dalibor Quizás no soy el mejor, pero tengo una buena comprensión de los puntos de referencia de Java, por lo que, a menos que pueda señalar un problema específico, es engañoso y no continuaré la conversación con usted en esas condiciones. - Ilya Gazmán
Principalmente estoy de acuerdo con Dalibor. Dice que tiene una "buena comprensión de los puntos de referencia de Java", pero parece que ha implementado el enfoque más ingenuo y aparentemente ignora los problemas conocidos de este enfoque. Para empezar, lea todas las publicaciones sobre esta pregunta: stackoverflow.com/questions/504103/… - Davids
41
Usaría algunos trucos de Java 8.
public static String streamToString(final InputStream inputStream) throws Exception {
// buffering optional
try
(
final BufferedReader br
= new BufferedReader(new InputStreamReader(inputStream))
) {
// parallel optional
return br.lines().parallel().collect(Collectors.joining("\n"));
} catch (final IOException e) {
throw new RuntimeException(e);
// whatever.
}
}
Esencialmente lo mismo que algunas otras respuestas, excepto más concisas.
Respondido 15 Jul 15, 12:07
35
Hice algunas pruebas de cronometraje porque el tiempo siempre importa.
Intenté obtener la respuesta en una cadena de 3 formas diferentes. (mostrado a continuación)
Dejé los bloques try / catch por el bien de la legibilidad.
Para dar contexto, este es el código anterior para los 3 enfoques:
String response;
String url = "www.blah.com/path?key=value";
GetMethod method = new GetMethod(url);
int status = client.executeMethod(method);
1)
response = method.getResponseBodyAsString();
2)
InputStream resp = method.getResponseBodyAsStream();
InputStreamReader is=new InputStreamReader(resp);
BufferedReader br=new BufferedReader(is);
String read = null;
StringBuffer sb = new StringBuffer();
while((read = br.readLine()) != null) {
sb.append(read);
}
response = sb.toString();
3)
InputStream iStream = method.getResponseBodyAsStream();
StringWriter writer = new StringWriter();
IOUtils.copy(iStream, writer, "UTF-8");
response = writer.toString();
Entonces, después de ejecutar 500 pruebas en cada enfoque con los mismos datos de solicitud / respuesta, aquí están los números. Una vez más, estos son mis hallazgos y es posible que sus hallazgos no sean exactamente los mismos, pero escribí esto para dar alguna indicación a otros de las diferencias de eficiencia de estos enfoques.
Rangos:
Enfoque # 1
Enfoque n. ° 3: 2.6% más lento que el n. ° 1
Enfoque n. ° 2: 4.3% más lento que el n. ° 1
Cualquiera de estos enfoques es una solución adecuada para obtener una respuesta y crear una cadena a partir de ella.
Respondido 17 Oct 17, 09:10
34
Solución pura de Java usando Corrientes, funciona desde Java 8.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
// ...
public static String inputStreamToString(InputStream is) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
Como lo menciona Christoffer Hammarström a continuación otra respuesta Es más seguro especificar explícitamente el charset. Es decir, el constructor InputStreamReader se puede cambiar de la siguiente manera:
new InputStreamReader(is, Charset.forName("UTF-8"))
contestado el 23 de mayo de 17 a las 13:05
27
Aquí está la respuesta de más o menos sampath, limpiada un poco y representada como una función:
String streamToString(InputStream in) throws IOException {
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
for(String line = br.readLine(); line != null; line = br.readLine())
out.append(line);
br.close();
return out.toString();
}
Respondido el 12 de Septiembre de 12 a las 19:09
26
Si te sientes aventurero, puedes mezclar Scala y Java y terminar con esto:
scala.io.Source.fromInputStream(is).mkString("")
La combinación de código y bibliotecas de Java y Scala tiene sus ventajas.
Vea la descripción completa aquí: Manera idiomática de convertir un InputStream en un String en Scala
contestado el 23 de mayo de 17 a las 13:05
22
Si no puede usar Commons IO (FileUtils / IOUtils / CopyUtils), aquí hay un ejemplo usando un BufferedReader para leer el archivo línea por línea:
public class StringFromFile {
public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
InputStream is = StringFromFile.class.getResourceAsStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is/*, "UTF-8"*/));
final int CHARS_PER_PAGE = 5000; //counting spaces
StringBuilder builder = new StringBuilder(CHARS_PER_PAGE);
try {
for(String line=br.readLine(); line!=null; line=br.readLine()) {
builder.append(line);
builder.append('\n');
}
}
catch (IOException ignore) { }
String text = builder.toString();
System.out.println(text);
}
}
O si desea velocidad bruta, propondría una variación de lo que sugirió Paul de Vrieze (que evita el uso de StringWriter (que usa un StringBuffer internamente):
public class StringFromFileFast {
public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
InputStream is = StringFromFileFast.class.getResourceAsStream("file.txt");
InputStreamReader input = new InputStreamReader(is/*, "UTF-8"*/);
final int CHARS_PER_PAGE = 5000; //counting spaces
final char[] buffer = new char[CHARS_PER_PAGE];
StringBuilder output = new StringBuilder(CHARS_PER_PAGE);
try {
for(int read = input.read(buffer, 0, buffer.length);
read != -1;
read = input.read(buffer, 0, buffer.length)) {
output.append(buffer, 0, read);
}
} catch (IOException ignore) { }
String text = output.toString();
System.out.println(text);
}
}
Respondido el 05 de enero de 19 a las 10:01
20
Asegúrese de cerrar las transmisiones al final si usa Stream Readers
private String readStream(InputStream iStream) throws IOException {
//build a Stream Reader, it can read char by char
InputStreamReader iStreamReader = new InputStreamReader(iStream);
//build a buffered Reader, so that i can read whole line at once
BufferedReader bReader = new BufferedReader(iStreamReader);
String line = null;
StringBuilder builder = new StringBuilder();
while((line = bReader.readLine()) != null) { //Read till end
builder.append(line);
builder.append("\n"); // append new line to preserve lines
}
bReader.close(); //close all opened stuff
iStreamReader.close();
//iStream.close(); //EDIT: Let the creator of the stream close it!
// some readers may auto close the inner stream
return builder.toString();
}
EDITAR: En JDK 7+, puede usar la construcción try-with-resources.
/**
* Reads the stream into a string
* @param iStream the input stream
* @return the string read from the stream
* @throws IOException when an IO error occurs
*/
private String readStream(InputStream iStream) throws IOException {
//Buffered reader allows us to read line by line
try (BufferedReader bReader =
new BufferedReader(new InputStreamReader(iStream))){
StringBuilder builder = new StringBuilder();
String line;
while((line = bReader.readLine()) != null) { //Read till end
builder.append(line);
builder.append("\n"); // append new line to preserve lines
}
return builder.toString();
}
}
Respondido 24 Feb 17, 19:02
19
Esta es una respuesta adaptada de org.apache.commons.io.IOUtils
código fuente, para aquellos que quieren tener la implementación de Apache pero no quieren toda la biblioteca.
private static final int BUFFER_SIZE = 4 * 1024;
public static String inputStreamToString(InputStream inputStream, String charsetName)
throws IOException {
StringBuilder builder = new StringBuilder();
InputStreamReader reader = new InputStreamReader(inputStream, charsetName);
char[] buffer = new char[BUFFER_SIZE];
int length;
while ((length = reader.read(buffer)) != -1) {
builder.append(buffer, 0, length);
}
return builder.toString();
}
Respondido 10 Oct 15, 05:10
19
Este es bueno porque:
- Maneja con seguridad el juego de caracteres.
- Tú controlas el tamaño del búfer de lectura.
- Puede aprovisionar la longitud del constructor y no tiene que ser un valor exacto.
- Está libre de dependencias de la biblioteca.
- Es para Java 7 o superior.
¿Cómo hacerlo?
public static String convertStreamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder(2048); // Define a size if you have an idea of it.
char[] read = new char[128]; // Your buffer size.
try (InputStreamReader ir = new InputStreamReader(is, StandardCharsets.UTF_8)) {
for (int i; -1 != (i = ir.read(read)); sb.append(read, 0, i));
}
return sb.toString();
}
Para JDK 9
public static String inputStreamString(InputStream inputStream) throws IOException {
try (inputStream) {
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
}
Respondido el 20 de junio de 19 a las 06:06
18
Use el java.io.InputStream.transferTo (OutputStream) soportado en Java 9 y el ByteArrayOutputStream.toString (Cadena) que toma el nombre del juego de caracteres:
public static String gobble(InputStream in, String charsetName) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in.transferTo(bos);
return bos.toString(charsetName);
}
respondido 28 nov., 17:14
17
Otro, para todos los usuarios de Spring:
import java.nio.charset.StandardCharsets;
import org.springframework.util.FileCopyUtils;
public String convertStreamToString(InputStream is) throws IOException {
return new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8);
}
Los métodos de utilidad en org.springframework.util.StreamUtils
son similares a los de FileCopyUtils
, pero dejan el arroyo abierto cuando terminan.
Respondido 21 Jul 17, 11:07
16
Aquí está el método completo para convertir InputStream
dentro String
sin utilizar ninguna biblioteca de terceros. Usar StringBuilder
para entornos de un solo subproceso de lo contrario utilizar StringBuffer
.
public static String getString( InputStream is) throws IOException {
int ch;
StringBuilder sb = new StringBuilder();
while((ch = is.read()) != -1)
sb.append((char)ch);
return sb.toString();
}
Respondido el 16 de diciembre de 15 a las 09:12
15
Aquí se explica cómo hacerlo usando solo el JDK usando búferes de matriz de bytes. Así es en realidad el commons-io IOUtils.copy()
todos los métodos funcionan. Puedes reemplazar byte[]
char[]
si estás copiando desde un Reader
en lugar de un InputStream
.
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
...
InputStream is = ....
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
byte[] buffer = new byte[8192];
int count = 0;
try {
while ((count = is.read(buffer)) != -1) {
baos.write(buffer, 0, count);
}
}
finally {
try {
is.close();
}
catch (Exception ignore) {
}
}
String charset = "UTF-8";
String inputStreamAsString = baos.toString(charset);
Respondido 13 ago 14, 05:08
15
Los usuarios de Kotlin simplemente hacen:
println(InputStreamReader(is).readText())
mientras
readText()
es el método de extensión integrado de la biblioteca estándar de Kotlin.
Respondido 04 Feb 15, 01:02
14
String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {
try (
final StringWriter writer = new StringWriter();
final InputStreamReader reader = new InputStreamReader(inputStream, charset)
) {
reader.transferTo(writer);
return writer.toString();
}
}
- solución de biblioteca estándar pura de Java, sin bibliotecas
- desde Java 10 - Reader # transferTo (java.io.Writer)
- solución sin bucle
- sin manejo de caracteres de nueva línea
Respondido 05 Abr '20, 01:04
10
La forma más sencilla en JDK es con los siguientes fragmentos de código.
String convertToString(InputStream in){
String resource = new Scanner(in).useDelimiter("\\Z").next();
return resource;
}
Respondido 09 ago 16, 21:08
8
Aquí está mi Java 8 solución basada en nueva API de transmisión para recopilar todas las líneas de un InputStream
:
public static String toString(InputStream inputStream) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
return reader.lines().collect(Collectors.joining(
System.getProperty("line.separator")));
}
Respondido el 02 de Septiembre de 15 a las 12:09
8
En términos de reduce
y concat
se puede expresar en Java 8 como:
String fromFile = new BufferedReader(new
InputStreamReader(inputStream)).lines().reduce(String::concat).get();
Respondido el 20 de junio de 18 a las 08:06
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java string io stream inputstream or haz tu propia pregunta.
¿Responde esto a tu pregunta? ¿El escáner se salta nextLine () después de usar next () o nextFoo ()? - Kevin Anderson
Recuerde que debe tener en cuenta la codificación del flujo de entrada. El sistema predeterminado no es necesariamente siempre el que desea. Thorbjørn Ravn Andersen