Programa Java para converter uma string em InputStream

Neste programa, aprenderemos a converter uma string em um inputstream em Java.

Para entender este exemplo, você deve ter conhecimento dos seguintes tópicos de programação Java:

  • Java String
  • Classe Java InputStream
  • Classe Java ByteArrayInputStream

Exemplo: Programa Java para converter String em InputStream

 import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; public class Main ( public static void main(String args()) ( // Creates a string String name = "Programiz"; System.out.println("String is: " + name); try ( InputStream stream = new ByteArrayInputStream(name.getBytes(StandardCharsets.UTF_8)); System.out.println("InputStream: " + stream); // Returns the available number of bytes System.out.println("Available bytes at the beginning: " + stream.available()); // Reads 3 bytes from the stream stream stream.read(); stream.read(); stream.read(); // After reading 3 bytes // Returns the available number of bytes System.out.println("Available bytes at the end: " + stream.available()); stream.close(); ) catch (Exception e) ( e.getStackTrace(); ) ) )

Resultado

 String é: Programiz InputStream: java.io.ByteArrayInputStream@5479e3f Bytes disponíveis no início: 9 bytes disponíveis no final: 6

No exemplo acima, criamos uma string chamada name. Aqui, estamos convertendo a string no fluxo de entrada denominado stream.

O getBytes()método converte a string em bytes. Para saber mais, visite Java String getBytes ()

Artigos interessantes...