On Dec 4, 10:27 am, mars...@hotmail.com wrote:
> I have problem of finding the best solution to output the result to the
> screen or both the screen and file
[quoted text clipped - 6 lines]
>
> Any suggestion?
An idea is to use the MultiWriter Patricia Shanahan wrote as a reply to
your previous post.
Writer dup;
if (args.length > 0 && "file".equals(args[0])) {
dup = new MultiWriter(new FileWriter("Testfile.txt"));
} else if (args.length > 0 && "console".equals(args[0])) {
dup = new MultiWriter(new OutputStreamWriter(System.out));
} else { // both
dup = new MultiWriter(new FileWriter("Testfile.txt"), new
OutputStreamWriter(System.out));
}
lexExample.outStream = new PrintWriter(dup);
Regards,
Bart
Patricia Shanahan - 04 Dec 2006 13:15 GMT
> On Dec 4, 10:27 am, mars...@hotmail.com wrote:
>> I have problem of finding the best solution to output the result to the
[quoted text clipped - 26 lines]
>
> Bart
I canceled that post because in rereading I thought that the problem was
one at a time. Here is it again, in case it didn't get to the OP. I've
done limited testing, so use at your own risk. The main method can be
deleted, it is just for illustration and testing.
Incidentally, I picked extending Writer for two reasons:
1. It has only three abstract methods left to the subclass.
2. It stays in the character processing domain, leaving any character
mapping to get to a Stream to the caller.
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
/**
* Write to multiple Writer instances
*
*/
public class MultiWriter extends Writer {
private Writer[] writers;
/**
* New MultiWriter for specified writers. Note that flush is
* only done on explicit call.
*/
public MultiWriter(Writer... writers) {
this.writers = new Writer[writers.length];
for (int i = 0; i < writers.length; i++) {
this.writers[i] = writers[i];
}
}
@Override
public void write(char[] cbuf, int off, int len)
throws IOException {
for (Writer w : writers) {
w.write(cbuf, off, len);
w.flush();
}
}
@Override
public void flush() throws IOException {
for (Writer w : writers) {
w.flush();
}
}
@Override
public void close() throws IOException {
for (Writer w : writers) {
w.close();
}
}
public static void main(String[] args) throws IOException {
Writer console = new OutputStreamWriter(System.out);
Writer file = new FileWriter("Testfile.txt");
Writer dup = new MultiWriter(console, file);
PrintWriter print = new PrintWriter(dup);
print.printf("Hello, world");
print.println();
}
}