Merge pull request #15809 from anujgaud/system-in-read

[BAEL-7405] Add support for System read methods
This commit is contained in:
Maiklins 2024-02-13 07:55:13 +01:00 committed by GitHub
commit 1fb71a4cde
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,45 @@
package com.baeldung.systemin;
import java.io.IOException;
class SystemInRead {
static void readSingleCharacter() {
System.out.println("Enter a character:");
try {
int input = System.in.read();
System.out.println((char) input);
}
catch (IOException e) {
System.err.println("Error reading input: " + e.getMessage());
}
}
static void readMultipleCharacters() {
System.out.println("Enter characters (Press 'Enter' to quit):");
try {
int input;
while ((input = System.in.read()) != '\n') {
System.out.print((char) input);
}
} catch (IOException e) {
System.err.println("Error reading input: " + e.getMessage());
}
}
static void readWithParameters() {
try {
byte[] byteArray = new byte[5];
int bytesRead;
int totalBytesRead = 0;
while ((bytesRead = System.in.read(byteArray, 0, byteArray.length)) != -1) {
System.out.print("Data read: " + new String(byteArray, 0, bytesRead));
totalBytesRead += bytesRead;
}
System.out.println("\nBytes Read: " + totalBytesRead);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.systemin;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.Test;
public class SystemInReadUnitTest {
@Test
void givenUserInput_whenUsingReadMultipleCharacters_thenRead() {
System.setIn(new ByteArrayInputStream("Hello\n".getBytes()));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
SystemInRead.readMultipleCharacters();
assertEquals("Enter characters (Press 'Enter' to quit):\n" + "Hello", outputStream.toString().trim());
}
@Test
void givenUserInput_whenUsingReadSingleCharacter_thenRead() {
System.setIn(new ByteArrayInputStream("A".getBytes()));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
SystemInRead.readSingleCharacter();
assertEquals("Enter a character:\nA", outputStream.toString().trim());
}
@Test
void givenUserInput_whenUsingReadWithParameters_thenRead() {
System.setIn(new ByteArrayInputStream("ABC".getBytes()));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
SystemInRead.readWithParameters();
assertEquals("Data read: ABC\n" + "Bytes Read: 3", outputStream.toString().trim());
}
}