Skip to content

Commit c651b85

Browse files
authored
Add read methods
1 parent e020a58 commit c651b85

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

  • core-java-modules/core-java-console/src/main/java/com/baeldung/systemin
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.baeldung.systemin;
2+
3+
import java.io.IOException;
4+
5+
class SystemInRead {
6+
static void readSingleCharacter() {
7+
System.out.println("Enter a character:");
8+
try {
9+
int input = System.in.read();
10+
System.out.println((char) input);
11+
}
12+
catch (IOException e) {
13+
System.err.println("Error reading input: " + e.getMessage());
14+
}
15+
}
16+
static void readMultipleCharacters() {
17+
System.out.println("Enter characters (Press 'Enter' to quit):");
18+
try {
19+
int input;
20+
while ((input = System.in.read()) != '\n') {
21+
System.out.print((char) input);
22+
}
23+
} catch (IOException e) {
24+
System.err.println("Error reading input: " + e.getMessage());
25+
}
26+
}
27+
28+
static void readWithParameters() {
29+
try {
30+
byte[] byteArray = new byte[5];
31+
int bytesRead;
32+
int totalBytesRead = 0;
33+
34+
while ((bytesRead = System.in.read(byteArray, 0, byteArray.length)) != -1) {
35+
System.out.print("Data read: " + new String(byteArray, 0, bytesRead));
36+
totalBytesRead += bytesRead;
37+
}
38+
39+
System.out.println("\nBytes Read: " + totalBytesRead);
40+
41+
} catch (IOException e) {
42+
e.printStackTrace();
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)