Reputation: 733
I am writing compressed data to disk using GZIPOutputStream in an asynchronous manner
I want to know the size of data already written so I can close the file once it reaches a limit
ByteBuffer src;
//..
//data added to src here
//..
File theFile = new File("hello.gz");
FileOutputStream fos = new FileOutputStream(theFile);
GZIPOutputStream zs = new GZIPOutputStream(fos);
BufferedWriter zipwriter = new BufferedWriter(new OutputStreamWriter(zs, "UTF-8"));
(while_more_data)
{
zipwriter.write(src.get());
// check current file size here and close file if limit is reached
}
Upvotes: 2
Views: 2361
Reputation: 7916
Or if you don't wan't to pull in an entire library like Guava or Commons-IO, you can just extend the GZIPOutputStream and obtain the data from the associated Deflater like so:
public class MyGZIPOutputStream extends GZIPOutputStream {
public GZIPOutputStream(OutputStream out) throws IOException {
super(out);
}
public long getBytesRead() {
return def.getBytesRead();
}
public long getBytesWritten() {
return def.getBytesWritten();
}
public void setLevel(int level) {
def.setLevel(level);
}
}
Upvotes: 0
Reputation: 24444
Wrap your FileOutputStream
into another output stream that is able to count the number of bytes written, like CountingOutputStream
provided by third party library Jakarta Commons IO, or CountingOutputStream
from Guava.
The implementation could be something like:
ByteBuffer src;
//..
//data added to src here
//..
File theFile = new File("hello.gz");
try (FileOutputStream fos = new FileOutputStream(theFile);
CountingOutputStream cos = new CountingOutputStream(fos);
GZIPOutputStream zs = new GZIPOutputStream(cos);
BufferedWriter zipwriter = new BufferedWriter(new OutputStreamWriter(zs, "UTF-8"))) {
(while_more_data) {
zipwriter.write(src.get());
zipwriter.flush(); // make sure, data passes cos
if (cos.getByteCount() >= limit) {
// limit reached
}
}
}
Upvotes: 4