3

How to count number of bytes of this binary file (t.dat) without running this code (as a theoretical question) ? Assuming that you run the following program on Windows using the default ASCII encoding.

public class Bin {
     public static void main(String[] args){
     DataOutputStream output = new DataOutputStream(
            new FileOutputStream("t.dat"));
     output.writeInt(12345);
     output.writeUTF("5678");
     output.close();
     }
}
Robin Green
  • 32,079
  • 16
  • 104
  • 187
dave
  • 61
  • 6
  • This have nothing to do with OOP. Removed irrelevant tags. Please ensure the tags you use for future questions are justifiable. In fact, this seems like a CS question, where code isn't even required, rather just the information such as language, encoding & the type/amount of data. – Vince May 05 '18 at 01:41

1 Answers1

2

Instead of trying to compute the bytes output by each write operation, you could simply check the length of the file after it's closed using new File("t.dat").length().

If you wanted to figure it out without checking the length directly, an int takes up 4 bytes, and something written with writeUTF takes up 2 bytes to represented the encoded length of the string, plus the space the string itself takes, which in this case is another 4 bytes -- in UTF-8, each of the characters in "5678" requires 1 byte.

So that's 4 + 2 + 4, or 10 bytes.

kshetline
  • 12,547
  • 4
  • 37
  • 73
  • This is a theory exam question (on paper) how to count it without running the code ? – dave May 05 '18 at 00:53
  • I amended my answer above. – kshetline May 05 '18 at 00:56
  • 2
    Note that the details of what `writeUTF` and `writeInt` output are specified in the javadocs. But this is (IMO) a poor exam question if they expect you to be able to recite details as obscure as these. – Stephen C May 05 '18 at 02:05
  • (According to the javadoc writeUTF outputs **exactly** two bytes for the length. But, interestingly, it doesn't say what happens for a string with > 2^16 characters. The answer is that it throws `UTFDataFormatException` ...) – Stephen C May 05 '18 at 02:10
  • Indeed, anything that uses _modified UTF_ is obscure (except JNI—no, JNI _is_ obscure). – Tom Blodget May 05 '18 at 18:35