System.out.println
method has print
and newLine
methods. There is no way to capture only System.out.println
method, you should capture all System.out.print
methods with changing System.out
variable.
System.out.println
jdk implementation:
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
Text collector output stream class for capturing System.out.print
content:
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class TextCollector extends OutputStream {
private final List<String> lines = new ArrayList<>();
private StringBuilder buffer = new StringBuilder();
@Override
public void write(int b) throws IOException {
if (b == '\n') {
lines.add(buffer.toString());
buffer = new StringBuilder();
} else {
buffer.append((char) b);
}
}
public List<String> getLines() {
return lines;
}
}
Example test implementation:
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
// store current output
PrintStream tmpOut = System.out;
// change stream into text collector
TextCollector textCollector = new TextCollector();
System.setOut(new PrintStream(textCollector));
// collect lines
System.out.println("Test-1");
System.out.println("Test-2");
// print lines to console
System.setOut(tmpOut);
List<String> lines = textCollector.getLines();
for (String line : lines) {
System.out.println(line);
}
}
}