yuris
yuris

Reputation: 1139

Count the bytes written to file via BufferedWriter

I am using BufferedWriter to write text with specific encoding to file, I want to count the file size in bytes before I close the file.

bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),encoding),bsize);
bw.write(string); 

My plan was to use string.getBytes() but this method doesn't allow to provide specific encoding (and I can't override the default encoding property).

Upvotes: 0

Views: 1709

Answers (2)

misberner
misberner

Reputation: 3678

If you're looking for a method that works regardless of whether you're appending or not and does not duplicate data just for counting, store the reference to the FileOutputStream in a variable and access the FileChannel through getFileChannel(). You can call long position() before and after the data has been written, and the difference of the values will give you the number of bytes that have been written.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Use String#getBytes(encoding) instead

Upvotes: 2

Related Questions