この質問は、この質問で受け入れられた回答のフォローアップです。私は Aaron によって提案されたアプローチを実装しようとしています: FileOutputStream をラップして、これまでに書き込まれたバイト数のカウントを保持するロジックを含めます。ただし、このアプローチは期待どおりに機能していないようです。OutputStreamWriter は、 FileOutputStream.write() メソッドへの呼び出しを委譲する前にデータをバッファリングしているStreamEncoderを使用しているようです。
ここに小さなデモがあります:
package Utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MyFileOutputStream extends FileOutputStream{
private int byteCount;
public int getByteCount() {
return byteCount;
}
public void setByteCount(int byteCount) {
this.byteCount = byteCount;
}
public MyFileOutputStream(String arg0) throws FileNotFoundException {
super(arg0);
byteCount = 0;
}
@Override
public void write(byte[] b) throws IOException{
byteCount += b.length;
super.write(b);
}
@Override
public void write(byte[] b , int off , int len) throws IOException{
byteCount += len;
super.write(b, off, len);
}
}
そしてドライバークラス:
package main;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import Utils.MyFileOutputStream;
public class Driver {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
MyFileOutputStream fos = new MyFileOutputStream("testFile");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for(int i=0;i<1000;i++){
bw.write("Writing this string\n");
System.out.println("Bytes Written : "+fos.getByteCount());
}
bw.close();
System.out.println(fos.getByteCount());
}
}
出力:-
書き込まれたバイト: 0
書き込まれたバイト: 0
...
書き込まれたバイト: 8192
書き込まれたバイト: 8192
...
出力に示されているように、StreamEncoder は、FileOutputStream の write() メソッドへの呼び出しを委譲する前に、最大 8192 バイトをバッファリングします。任意の時点でファイルに書き込まれたバイト数を取得するための回避策はありますか?