This question is a follow up to the accepted answer in this question. I am trying to implement the approach suggested by Aaron : Wrapping the FileOutputStream to include the logic to keep a count of the no.of bytes written so far. However the approach quite doesn't seem to work as expected. The OutputStreamWriter seems to be using a StreamEncoder which is buffering the data before delegating call to the FileOutputStream.write() method.
Here is a small Demo :
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);
}
}
And Driver Class :
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());
}
}
Output :-
Bytes Written : 0
Bytes Written : 0
...
Bytes Written : 8192
Bytes Written : 8192
...
As shown by the output the StreamEncoder buffers up to 8192 bytes before delegating call to write() method of FileOutputStream. Is there any work around for this to get the no.of bytes written to a file at any instant of time ?