tags:

views:

71

answers:

1

If I call writeUTF(String) on a DataOutput object, is there a way to tell how many bytes were actually written?

E.g.:

public int write(DataOutput output) throws IOException {
   output.writeUTF(this.messageString);
   int numberOfBytesWritten = ???;
   return numberOfBytesWritten;
}

The only method that comes to mind is to create a DataOutputStream, write the string to that and check the size, then rewrite the string to the actual output. But that seems inefficient.

+1  A: 

One easy way is to write the String seperately to a DataOutputStream wrapping a ByteArrayOutputStream, then close() he DataOutputStream and get the backing byte array from the BAOS and see how long it is.

It might even be simpler to wrap your own implementation of OutputStream that overrides the single write(int b) method to simply add 1 to the classes' internal counter for every call e.g.

public class MyOS extends OutputStream
{
   private int count = 0;
   public void write(int b){ count++; }
   public int getCount() { return count; }
}
...
GregS