为什么BufferedOutputStream不输出数据?

时间:2014-01-15 12:31:26

标签: java

我尝试创建自己的类,使用BufferedStream将系统输出流输出到控制台和文件。但是BufferedOutputStream中没有显示数据。我该如何解决这个问题?

package com.library.stream;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DoubleEndedStream {
InputStream theInput;
OutputStream theOutput;

public static void main(String[] args) throws IOException, FileNotFoundException {
    DoubleEndedStream sr = new DoubleEndedStream(System.in, System.out);
    sr.doublingTheStream();
}

public DoubleEndedStream(InputStream in, OutputStream out) {
    theInput = in;
    theOutput = out;    
}

public void doublingTheStream() throws IOException, FileNotFoundException  {
    try {
        FileOutputStream fos = new FileOutputStream("C:\\log.txt");
        BufferedOutputStream bout1 = new BufferedOutputStream(fos);
        BufferedOutputStream bout2 = new BufferedOutputStream(theOutput);
        try {
            while (true) {
                int datum = theInput.read();
                if (datum == -1) break;
                bout1.write(datum);
                bout2.write(datum);
            }
            bout1.flush();
            bout2.flush();
        } catch (IOException e) {
            System.err.println("Couldn't read from System.in!");
        }

        bout1.close();
        bout2.close();
        fos.close();
    } catch (FileNotFoundException e) {
        System.err.println("Couldn't find log.txt");
    }
}

}

1 个答案:

答案 0 :(得分:0)

由于theInputSystem.in,只要您不关闭它,(unix中为ctrl-d),它就不会返回-1,而是挂起并等待输入。由于您仅在收到flush()时才会执行-1,因此您永远不会达到这一点。请尝试在write()之后进行刷新。