Dans ce programme, nous allons apprendre à convertir une chaîne en flux d'entrée en Java.
Pour comprendre cet exemple, vous devez avoir la connaissance des rubriques de programmation Java suivantes:
- Chaîne Java
- Classe InputStream Java
- Classe Java ByteArrayInputStream
Exemple: programme Java pour convertir String en 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(); ) ) )
Production
La chaîne est: Programiz InputStream: java.io.ByteArrayInputStream@5479e3f Octets disponibles au début: 9 Octets disponibles à la fin: 6
Dans l'exemple ci-dessus, nous avons créé une chaîne nommée name. Ici, nous avons converti la chaîne en flux d'entrée nommé stream.
La getBytes()
méthode convertit la chaîne en octets. Pour en savoir plus, visitez Java String getBytes ()