我嘗試使用BufferedStream創建我自己的類,以便將系統輸出流輸出到控制檯並同時輸出到文件。但是數據不會從BufferedOutputStream中出現。我應該如何解決這個問題?爲什麼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");
}
}
}
您是否遇到BufferedOutputStrem控制檯,文件或兩者的問題? – Narkha
你需要刷新你的流。它在寫入之前填滿緩衝區。 – Kayaman
它是否拋出異常?我認爲如果(datum == -1)中斷;這部分在程序啓動時執行,因爲可能沒有數據並且循環被破壞。 – SaurabhJinturkar