go to previous page   go to home page   go to next page
out.writeInt( 0 );
out.writeDouble( 12.45 );

Answer:

An int is 4 bytes (32 bits), a double is 8 bytes (64 bits) so the total is 12 bytes.

The value of the number does not affect how many bytes are written. An int is 32 bits, regardless of its value.

Of course, a program that reads a file written by the above statements must be careful to read the data using the correct methods for the data types written.


The Byte Counter

import java.io.*;
class ByteCounter
{
  public static void main ( String[] args ) throws IOException
  {
    String fileName = "mixedTypes.dat" ;

    DataOutputStream dataOut = new DataOutputStream(
        new BufferedOutputStream(
            new FileOutputStream( fileName  ) ) );

    dataOut.writeInt( 0 );
    System.out.println( dataOut.size()  + " bytes have been written.");

    dataOut.writeDouble( 12.45 );
    System.out.println( dataOut.size()  + " bytes have been written.");

    dataOut.close();
  }
}

DataOutputStream counts the number of bytes that have been written to the stream. The method size() returns this value as an int. The program demonstrates this. When the program runs, it writes an int and a double to the file, and writes the following to the monitor:

C:\Programs>java  ByteCounter
4 bytes have been written.
12 bytes have been written.

C:\Programs>

The method returns the total count of bytes written, not the number written by the last method call.


QUESTION 13:

Can several different data types be written to the same file?


go to previous page   go to home page   go to next page