Reading System.out.println(Text) from another class
Basically I am making a class that is supposed to read a series of integers from another class.
The other class is System.out.printing the integers in the following order:
i i i i
i i i i
... etc.
So I basically want to make a String file or whatever works, that I can read this output from in the 开发者_开发百科first class.
I'm pretty lost, I don't know if I should create a Scanner(System.in), and if so, what to do with it.
I guess this is a pretty open question, so apologies in advance.
Redirecting System.out
is one solution, but that would redirect System.out
for all classes - you can't (easily) redirect for this one class exclusivly.
Maybe this "other class" is under your control and you can take this as an oppertunity to restructure the code. So maybe you have something like:
public void print(int[] values) {
// ...
System.out.println(result);
}
then you could change the code to
public String prepareResult(int[] values) {
// ...
return result;
}
public void print(int[] values) {
System.out.println(prepareResult(values));
}
and call the "prepareResult" method if you need the output in a String.
Basically I agree with guys that actually said that your design should be changed and the "other class" should just prepare result and return it.
But if this "other class" is not under your control I'd suggest you the following.
- use System.setOut() to send stdout to special stream.
- implement this special stream as following: It should get stack trace and discover where it was invoked from. If it is called form the "other class" do something to notify it (write data to special queue or so on) Otherwise just print to stdout.
If you are not familiar with API, here are some tips that will help you to implement it.
- new Throwable().getStackTrace()[0].getClassName() returns the class that called this code.
- Implementing of your own outptut stream is simple too.
public class FilterOutputStream extends OutputStream {
private OutputStream payload;
public FilterOutputStream(OutputStream payload) {
this.payload = payload;
}
public void write(int b) throws IOException {
if (isSpecialClass()) {
specialWrite(b);
} else {
payload.write(b);
}
}
public void flush() throws IOException {
payload.flush();
}
public void close() throws IOException {
payload.close();
}
public boolean isSpecialClass() {
return "MySpecialClass".equals(new Throwable().getStackTrace()[0].getClassName());
}
}
I did not try this code, so it probably contains even syntax errors, but it illustrates the general idea. I hope this helps.
You could use System.setOut() and System.setErr() to redirect standard output on a different stream (and then pipe that stream to your input).
精彩评论