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

Answer:

Does FileOutputStream itself provide a way to write an int to a disk?   No

Does DataOutputStream provide a way to write an int to a stream?   Yes


Example Program

import java.io.*;
class WriteInts
{

 public static void main ( String[] args ) 
 {
   String fileName = "intData.dat" ;
   int value0 = 0, value1 = 1, value255 = 255, valueM1 = -1;

   try
   {      
     DataOutputStream out = new DataOutputStream( new FileOutputStream( fileName  ) );

     out.writeInt( value0 );      // The writeInt method of DataOutputStream
     out.writeInt( value1 );      // writes 4-byte ints to the stream
     out.writeInt( value255 );
     out.writeInt( valueM1 );
     out.close();                 // might throw IOException
   }
   catch ( IOException iox )
   {
     System.out.println("Problem writing " + fileName );
   }

 }
}

In this program, the FileOutputStream constructor opens the file intData.dat for writing. A new file is created; if an old file has the same name it will be deleted. Then a DataOutputStream is connected to the FileOutputStream.

DataOutputStream has methods for writing primitive data to a output stream. The writeInt() method writes the four bytes of an int datatype to the stream.

More DataOutputStream methods are described below.

The program writes four integers to the output stream and then closes the stream. Always close an output stream to ensure that the operating system actually writes the data.

Note: The exact bit pattern of each int is written to the disk file. Nothing is translated into characters.


QUESTION 4:

The program writes four 32-bit int values. How big is the disk file?


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