Sequential file access

Objectives

  • Use sequential file I/O in Java
  • Discuss the differences between using sequential and random file access
  • Discuss the differences between using variable and fixed length records

File access overview

  • Files help to provide persistent data
  • Files are usually stored on secondary memory devices
  • Sequential access means records are accessed in order (from the front or end of a file)
  • Random access means that records can be processed in any order
  • Text files are usually sequential access
  • Fixed-length records make random access easier becasue you can immediately determine where each record is located
  • Updating a variable-length record usually means having to rewrite the entire file with the updated information
  • Taking care of closing a file to free resources can be tricky if errors occur
  • Java has try-with-resources to make closing a file automatic when done processing or in the case of an error (see the example in the list below)
  • Java also has a way of reading all the lines of a file at once into a list to make processing easier (see the example in the list below)

Sequential file I/O

  • Need to use: import java.io.*;
  • Remember to catch exceptions on all file I/O operations or specify that the enclosing method throws that exception.
  • Sun has made file I/O easier in recent versions of Java. You should at the least know how to do the simple file I/O for this course, and be able to look up the more complex file I/O when you need it.
  • See FileInput.java from CIS 160
  • See FileOutput.java from CIS 160
  • See SimpleFileIO.java: file I/O using FileReader, Scanner, PrintWriter
  • See ReadAllLines.java: reads all the contents of a text file at once into a list of Strings
  • See ReadWithResources.java: uses BufferedReader and try-with-resources to automatically take care of closing a file
  • See Course.java: class to hold data for UseCourse*.java programs below
  • See UseCourse.java: sequential file output using Formatter class
  • See UseCourse2.java: variation of UseCourse.java
  • See UseCourse3.java: reads data files created by UseCourse.java and UseCourse2.java
  • Objects can be directly written to and read from files if they implement the Serializable interface
  • See SerialTest.java: reads/writes objects from/to files using Serializable interface
  • See TestSeq1.java: sequential output of records; interactive input
  • See TestSeq2.java: sequential reading and display of sequential records; splitting fields
  • See TestSeq3.java: sequential output of serialized objects
  • See TestSeq4.java: sequential input of serialized objects