OutputStreamWriter写()

时间:2013-12-21 07:24:13

标签: java 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();
}   

}

但是当我尝试运行主类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()));
    }
}

1 个答案:

答案 0 :(得分:0)

TracingOutputStream中使用的OutputStreamWriter永远不会关闭。关闭它,输出将突然出现在输出文件中。