Files & Streams
Files & Streams
Farwah Sahar
java.io.File
• java.io.File is the central class in working with files and directories.
f= new File(dir, fname); Create File object for directory. s= f.toURL(); path with "file:" prefix and /'s. Directory paths end with /.
public static constants s= f.toURI(); path with "file:" prefix and /'s. Directory paths end with /.
• There are three predefined I/O streams that use the console.
• These are equivalent to Unix standard input, error, and output
streams.
• System.in // an InputStream.
• System.out // a PrintStream to write to console.
• System.err //.
11
Creating a Sequential-Access Text File
• Java imposes no structure on a file, records do not exist as part of the Java
language
• Programmer must structure files
• Formatter class can be used to open a text file for writing
– Use method close to close the Formatter object (if method not called,
OS normally closes file when program exits)
12
Creating a Sequential-Access Text File
• Possible exceptions
13
Reading Data from a Sequential-Access Text
File
• Data is stored in files so that it may be retrieved for processing when
needed
• Scanner object can be used to read data sequentially from a text file
– Data read from file using same methods as for keyboard input –
nextInt, nextDouble, next, etc.
14
Object Serialization
• With text files, data type information lost
15
Creating a Sequential-Access File Using Object Serialization:
16
Reading and Deserializing Data from a
Sequential-Access File
• To open a file for reading objects, create a FileInputStream wrapped by an
ObjectInputStream
17
Serializing & Deserializing
• The process of writing the state of an object to a byte stream is
known as Serialization.
• The process of Restoring the serialized objects is known as
Deserialization.
Random-Access Files
• Sequential-access files inappropriate for instant-access applications
• Easy to calculate (as a function of record size and record key) exact
location of any record relative to beginning of file
19
Creating a Random-Access File
• RandomAccessFile class
• Includes capabilities for reading and writing primitive-type values, byte arrays and
strings
• Using RandomAccessFile, program can read or write data beginning at location specified
by file-position pointer
• Methods readInt, readDouble, readChar used to read integer, double and character data
from file
• Methods writeInt, writeDouble, writeChars used to write integer, double and string data
to file
• File-open mode – specifies whether file is opened for reading (“r”), or for both reading
and writing (“rw”). File-open mode specified as second argument to RandomAccessFile
constructor
20
Creating a Random-Access File
21