120 likes | 294 Views
Files and Input/Output. Fall 2004 IST 311 Lecture 10. Files. File – collection of related records Student file Customer file Several types of file organization: Sequential Random Database. Streams. Streams provide communication of data at the byte level Used for reading or writing
E N D
Files and Input/Output Fall 2004 IST 311 Lecture 10
Files • File – collection of related records • Student file • Customer file • Several types of file organization: • Sequential • Random • Database
Streams • Streams provide communication of data at the byte level • Used for reading or writing • Streams for reading inherit from a common superclass – java.io.InputStream class • Streams for writing inherit from the common superclass – java.io.OutputStream
Files • There are two types of files in Java: • Binary files – processed as a sequence of bytes • Data is not very portable due to compatibility issues between different computer operating systems • Java binary files are platform independent; binary files created by a Java program can be interpreted by Java programs on any platform • Text files – processed as a sequence of characters • Portable files using ASCII code • Can be read and written by most text-processing programs
Streams • Java has a wide variety of streams for performing I/O • Defined in the java.io package which must be imported to perform any I/O • import java.io.*; • Generally, binary files are processed by subclasses of InputStream and OutputStream • Text files are processed by subclasses of FileReader and PrintWriter
Streams • The heirarchy of classes in package java.io can be seen at: http://java.sun.com/j2se/1.4.1/docs/api/java/io/package-tree.html
Reading from a File Use a 3 step algorithm • Connect an input stream to a file • Causes the file to open BufferedReader inFile; inFile = new BufferedReader (new FileReader("books.txt")); • Read data using a loop while (value != null) • Close the input stream (file) when finished inFile.close();
Reading from a File • If your file is not in the same folder as the Java program, specify the file directory: …..(new FileReader ( “a:\\data.txt”)); • If the input file does not exist, statements associated with it fail • throws a FileNotFoundException
Reading from a File • Remember that BufferedReader • throws an IOException
Writing to a File Use a 3 step algorithm • Connect an output stream to a file • Causes the file to open • If the file already exists, opening the file will destroy any data it previously held • If the file doesn’t exist, it will be created PrintWriter outFile; outFile = new PrintWriter(new FileWriter("report.txt"));
Writing to a File • Write data to the output stream, which passes it on to the file outFile.println(title); • Close the output stream when finished outFile.close();
Lab • Simple program to read from a file • Simple program to write to a file