Aquí está el ejemplo completo de cómo leer y convertir un archivo InputStream
a un String
. Los pasos involucrados son:
1) Inicialicé el archivo InputStream
después de convertir el contenido del archivo a bytes usando getBytes() method
y luego usando el ByteArrayInputStream
que contiene un búfer interno que contiene bytes que se pueden leer de la secuencia.
2) Lea el InputStream
utilizando InputStreamReader
.
3) Leer InputStreamReader
utilizando BufferedReader
.
4) Agregar cada línea a un archivo StringBuilder
objeto que ha sido leído por BufferedReader
.
5) Finalmente convertido el archivo StringBuilder
una cadena usando toString()
método.
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class Example { public static void main(String[] args) throws IOException { InputStreamReader isr = null; BufferedReader br = null; InputStream is = new ByteArrayInputStream("This is the content of my file".getBytes()); StringBuilder sb = new StringBuilder(); String content; try { isr = new InputStreamReader(is); br = new BufferedReader(isr); while ((content = br.readLine()) != null) { sb.append(content); } } catch (IOException ioe) { System.out.println("IO Exception occurred"); ioe.printStackTrace(); } finally { isr.close(); br.close(); } String mystring = sb.toString(); System.out.println(mystring); } }
Producción:
This is the content of my file