Java Reference
In-Depth Information
private
private final
final
JTextArea textArea
;
private
private final
final
StringBuilder sb
=
new
new
StringBuilder
();
public
public
TextAreaOutputStream
(
final
final
JTextArea textArea
) {
this
this
.
textArea
=
textArea
;
}
@Override
public
public
void
void
flush
(){ }
@Override
public
public
void
void
close
(){ }
@Override
public
public
void
void
write
(
int
int
b
)
throws
throws
IOException
{
iif
(
b
==
'\r'
)
return
return
;
iif
(
b
==
'\n'
) {
textArea
.
append
(
sb
.
toString
());
sb
.
setLength
(
0
);
}
sb
.
append
((
char
char
)
b
);
}
}
As with
Writer
, we only really need to override three methods; all the others (e.g.,
Sys-
tem.out.println()
) ultimately call down to this
write(int)
method. The class shown
here uses a
StringBuffer
to build up a line of text and, when a line ending comes along, ap-
pends the line to the
JTextArea
and resets the
StringBuffer
. A
\r
is ignored because on
UNIX a
\n
alone ends a line and on MS-DOS-based systems a
\r\n
ends a line.
It's not reprinted here, but there is a
JUnit
test for this class as well. One of the tests is simil-
ar to the one for
TextAreaWriter
, and the second uses
System.setOut()
followed by
Sys-
tem.out.println()
to ensure that everything works as expected. It does.
Here's a longer example of using this. I have an existing console-based
Check-
OpenMailRelay
program (derived from the mail sender in
Sending Email: For Real
), that I
use to test whether remote servers are willing to accept mail from unknown third parties and