-1
我寫了一個小程序來跟蹤inputstream和outputstream的方法回調。OutputStreamWriter write()
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();
}
}
但是當我試圖主類TracingOutputStreamMain運行,什麼也沒有寫。有人可以給我解釋嗎
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()));
}
}
除了你發佈的代碼甚至不能編譯?編號 –
我已編譯,但沒有發生。 log.write()被調用,但它不能寫出任何「log.txt」 – phongdt
你的主要方法永遠不會關閉也不會刷新任何流/作家。 –