V tem programu se bomo naučili pretvoriti niz v vhodni tok v Javi.
Če želite razumeti ta primer, morate poznati naslednje programske teme Java:
- Java Java
- Razred Java InputStream
- Razred Java ByteArrayInputStream
Primer: Java program za pretvorbo Stringa v 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(); ) ) )
Izhod
Niz je: Programiz InputStream: java.io.ByteArrayInputStream@5479e3f Na voljo bajti na začetku: 9 Na voljo bajti na koncu: 6
V zgornjem primeru smo ustvarili niz z imenom. Tu pretvorimo niz v vhodni tok z imenom stream.
getBytes()
Postopek pretvori niz v bajtih. Če želite izvedeti več, obiščite Java String getBytes ()