Txt 475 476 chapter 14 storing information in files a

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: t;. 475 476 Chapter 14: Storing information in files // A FileOutputStream object that represents a file on the disk is created first, and then that object is used to create a DataOutputStream object. You can think that the FileOutputStream object is controlled by the DataOutputStream object. The standard class DataOutputStream provides useful methods to write binary values to a file. If a file with the specified name already exists, it will be written over. NumbersToFile.java import java.io.* ; class NumbersToFile { public static void main( String not_in_use ) { try { FileOutputStream file_output_stream = new FileOutputStream( "NumbersToFile_output.data" ) ; DataOutputStream file_to_write = new DataOutputStream( file_output_stream ) ; int integer_to_file = 0x22 ; while ( integer_to_file < 0x77 ) { file_to_write.writeInt( integer_to_file ) ; integer_to_file = integer_to_file + 0x11 ; } file_to_write.writeShort( (short) 0x1234 ) ; file_to_write.writeDouble( 1.2345 ) ; file_to_write.writeBoolean( true ) ; file_to_write.writeBoolean( false ) ; file_to_write.writeUTF( "aaAAbbBB" ) ; byte bytes_to_file = { 0x4B, 0x61, 0x72, 0x69 } ; file_to_write.write( bytes_to_file, 0, 4 ) ; file_to_write.close() ; } catch ( Exception caught_exception ) { System.out.print( "\n File error. Cannot write to file." ) ; } } } Class DataOutputStream provides many methods that can write data items of different types to a file. Here, a method named write() writes four bytes from the array (referenced by) bytes_to_file. The writing begins from the array position whose index is 0 (the first array position). The bytes that are put to the array 0x4B, 0x61, 0x72, and 0x69 are the character codes of letters K, a, r, and i, respectively. NumbersToFile.java - 1. A program that stores numerical values to a binary file. 14.3 Handling files as binary files The execution of the program does not produce any output to the screen. All output goes to a file whose contents are shown here by using the previous example progra...
View Full Document

This document was uploaded on 01/20/2014.

Ask a homework question - tutors are online