13.07.2015 Views

I/O Fundamentals

I/O Fundamentals

I/O Fundamentals

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Java Input and Output• "r" - the file will be opened in "read" mode. If you try to use any outputmethods an exception will be thrown. If the file does not exist, aFileNotFoundException will be thrown. (More on I/O exceptions later!)• "rw" - the file will be opened in "read/write" mode. If the file does not exist, itwill try to create it.In either mode, you can use the read() methods as well as methods likereadInt(), readLong() and readUTF(). In read/write mode you can use thecorresponding write() methods.The big differences with RandomAccessFile are the positioning methods. You cancall getFilePointer() (which returns a long) at any time to determine thecurrent position within the file. This method is useful if you want to trackpositions as you write data to a file, possibly to write a corresponding index.You can jump to any location in the file as well, by calling seek() (passing a longvalue) to position the file pointer.As an example, we present a simple address book lookup program. There are twoparts to this example:• Address data creation - address-listing objects are created and their datastored in a RandomAccessFile, and a sequential index file tracks the positionof each record.• Address data lookup - user inputs a name to seek, the index is determined forthat name, and the name record is read from the RandomAccessFile.Note that this is not an example of efficient indexing; a very simple sequentialindex is used. For higher efficiency and easy relationship tracking, we recommendusing a database management system (DBMS).First, we create a class to represent the data. It has variables for all pieces ofinformation about a person. Note: to keep this example short, we have made theinstance variables package-accessible; in general, all data should be private,and only accessed through set()/get() methods!import java.io.*;/** A simple class that tracks address book* information for a person.* Note -- all data is package-accessible to keep the* example short. In general, all data _should_* be private and accessed through "get" and "set"Java Input and Output -44© 1996-2003 jGuru.com. All Rights Reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!