Under normal conditions the following code:
String[] outputStrings = {" Initial values: a = 1, b = 2 ", "Swapped values: a = 2, b = 1", ""};
System.out.println("array length: " + outputStrings.length);
int i = 0;
for (String line: outputStrings) {
String str = Integer.toString(i) + " : |" + line + "| ";
System.out.println(str);
//System.out.flush();
i++;
}
Has the following output:
array length: 3
0 : | Initial values: a = 1, b = 2 |
1 : |Swapped values: a = 2, b = 1|
2 : ||
However, the following code:
CommandLineTestScaffolding scaffolding;
scaffolding = new CommandLineTestScaffolding(ExchangeCL::main);
String[] inputStrings = {"1", "2"}; // string literals with integer numbers
String[] outputStrings = scaffolding.run(inputStrings);
scaffolding = null; //no longer necessary
System.out.println("array length: " + outputStrings.length);
int i = 0;
for (String line: outputStrings) {
String str = Integer.toString(i) + " : |" + line + "| ";
System.out.println(str);
//System.out.flush();
i++;
}
Has the following strange output:
array length: 1
0 : | Initial values: a = 1, b = 2
Swapped values: a = 2, b = 1
|
For information, the CommandLineTestScaffolding
is a simple contraption to temporary redirect System.out
to fetch command line output to an array of strings:
public class CommandLineTestScaffolding {
private Consumer<String[]> theMethod; //Place to store main method generating text output
public CommandLineTestScaffolding(Consumer<String[]> method) {
theMethod = method;
}
public String[] run(String[] args) {
// Create a stream to hold the output
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(outputStream);
// A variable to temporarily hold System.out stream
PrintStream oldOutputStream = null;
// Critical section. System.out must be restored to its original value
try {
System.out.flush(); // Clear buffer;
// IMPORTANT: Save the old System.out!
oldOutputStream = System.out;
// Use new wrapped byte array stream
System.setOut(printStream);
theMethod.accept(args); //Run the method. fill the stream
printStream.flush(); // Clear buffer;
}
finally {
// Put things back
System.setOut(oldOutputStream);
}
String[] output = outputStream.toString().split("/n"); //split into lines with regex
printStream = null;
outputStream = null;
return output;
}
}
What leads to such strange behaviour?