This repository has been archived on 2022-12-21. You can view files and clone it, but cannot push or open issues or pull requests.
sdm03/src/test/java/com/github/dtschust/zork/utils/IOWrapper.java

68 lines
2.0 KiB
Java

package com.github.dtschust.zork.utils;
import java.io.*;
/**
* IOWrapper allows to automatize in/out communication
*/
public class IOWrapper {
public final PrintStream console;
public final InputStream input;
private PrintStream printer;
private BufferedReader reader;
private final boolean verbose;
/** IOWrapper Constructor
* @param verbose should log on the console all command sent to / received by the game
*/
public IOWrapper(boolean verbose) {
this.verbose = verbose;
console = System.out;
input = System.in;
try{
final PipedOutputStream testInput = new PipedOutputStream();
final PipedOutputStream out = new PipedOutputStream();
final PipedInputStream testOutput = new PipedInputStream(out);
System.setIn(new PipedInputStream(testInput));
System.setOut(new PrintStream(out));
printer = new PrintStream(testInput);
reader = new BufferedReader(new InputStreamReader(testOutput));
} catch (IOException e) {
e.printStackTrace(console);
}
}
/** Sends a command to the game (and print it if verbose)
* @param line text to send to the game
*/
public void write(String line) {
printer.println(line);
if(verbose)
console.println("> " + line);
}
/** Receive a command from the game (and print it if verbose)
* @return line of text sent by the game
*/
public String read() {
String line = null;
try{
line = reader.readLine();
if(verbose)
console.println("< " + line);
} catch (IOException e) {
e.printStackTrace(console);
}
return line;
}
/** Restore the default System IO
*
*/
public void restore(){
System.setIn(input);
System.setOut(console);
}
}