【发布时间】:2020-06-03 10:09:54
【问题描述】:
正常情况下代码如下:
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++;
}
有以下输出:
array length: 3
0 : | Initial values: a = 1, b = 2 |
1 : |Swapped values: a = 2, b = 1|
2 : ||
但是,下面的代码:
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++;
}
有以下奇怪的输出:
array length: 1
0 : | Initial values: a = 1, b = 2
Swapped values: a = 2, b = 1
|
有关信息,CommandLineTestScaffolding 是临时重定向 System.out 以获取命令行输出到字符串数组的简单装置:
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;
}
}
是什么导致了这种奇怪的行为?
【问题讨论】:
-
拆分
\n而不是/n -
谢谢!我发现这对于 UNIX/OSX 和 Win 风格的换行符 .split("(\\r?\\n)", -1) 都有效。请参阅 stackoverflow.com/questions/454908/… 关于 CR 和 LF 以及 stackoverflow.com/questions/14602062/… 关于保留空行。
标签: java redirect junit console output