Dieses grundlegende Beispiel zeigt, wie man eine Zeichenkette (String) in einem Puffer (Buffer), der ganze 5 Bytes aufnehmen kann, abspeichert. Das Einlesen erfolgt dabei über einen Strom (Stream):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import java.io.ByteArrayInputStream; import java.io.InputStream; public static void main(String[] args) throws Exception { // Create a 5-Byte (40-Bit) buffer // Note: 5-Bytes are 5 characters in UTF-8 (8-Bit per character) int bufferSize = 5; byte[] buffer = new byte[bufferSize]; // Read bytes of a string into buffer String text = "Hello World!"; InputStream is = new ByteArrayInputStream(text.getBytes()); int bytesRead = is.read(buffer, 0, bufferSize); // Print result String bufferContent = new String(buffer); System.out.println("Bytes read: " + bytesRead); // Bytes read: 5 System.out.println("Result: " + bufferContent); // Result: Hello // Print result with a stream reader ByteArrayInputStream bais = new ByteArrayInputStream(buffer); BufferedReader br = new BufferedReader(new InputStreamReader(bais)); bufferContent = br.readLine(); System.out.println("Bytes read: " + bytesRead); // Bytes read: 5 System.out.println("Result: " + bufferContent); // Result: Hello } } |