The OutputStreamWriter used in TracingOutputStream is never closed. Close it, and the output will suddenly appear in the output file.
OutputStreamWriter write() [closed]
-
20-09-2022 - |
Pregunta
i wrote a small programm for keeping track of method call-back of inputstream and outputstream.
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class TracingOutputStream extends FilterOutputStream {
private String key;
private Writer log;
public TracingOutputStream(OutputStream sink, String key, OutputStream log) {
super(sink);
this.key = key;
this.log = new OutputStreamWriter(log);
}
@Override
public void write(byte[] b) throws IOException {
log.write(key + " write (byte [" + b.length + "])");
log.write(114);
super.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
log.write(key + " write (byte [" + b.length + "]" + " ," + off + len + ")");
super.write(b, off, len);
}
@Override
public void flush() throws IOException {
log.write(key + "flush()");
super.flush();
}
@Override
public void close() throws IOException {
log.write(key + "close()");
super.close();
}
}
But when i tried main class TracingOutputStreamMain to run, nothing was written. Could anybody explain it for me
import java.io.*;
import java.util.*;
public class TracingOutputStreamMain {
public static void main(String... args) throws IOException {
try(ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream();
OutputStream fout = new FileOutputStream("log.txt");
TracingOutputStream tracingOutput = new TracingOutputStream(bytesOutput, "ByteArray", fout);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(tracingOutput);
TracingOutputStream tracingBufferedOutput = new TracingOutputStream(bufferedOutput, "Buffered", fout)) {
for(String arg: args)
tracingBufferedOutput.write(arg.getBytes());
}
//System.out.println(Arrays.toString(bytesOutput.toByteArray()));
}
}
Solución
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow