Docsity

Java Programming: Reading and Writing Files - Object-Oriented Approach, Slides of Applications of Computer Sciences

Partial preview of the text

Download Java Programming: Reading and Writing Files - Object-Oriented Approach and more Slides Applications of Computer Sciences in PDF only on Docsity!

Chapter 12: Files

Object-Oriented Program

Development Using Java: A

Class-Centered Approach

Objectives

  • Files and Streams
  • Reading and Writing Character-Based Files
  • Reading and Writing Byte-Based Files
  • Application: Creating and Using a Holiday Table

Files and Streams

  • To store and retrieve data on a file, two items are

required:

  • File
  • File stream object

Files

  • Data file:
    • Collection of data
    • Stored together under a common name on a storage medium
    • Typically stored on:
      • Disk
      • Magnetic tape
      • CD-ROM

File Stream Objects

  • File stream:
    • One-way transmission path
    • Used to connect a file stored on a physical device to a program
  • Mode
    • Determines direction of data on transmission path

File Stream Objects

(continued)

  • Input file stream:
    • File stream that reads data from a file into a program
    • Automatically attempts to open an associated file in read mode
  • Output file stream:
    • File stream that writes data to a file
    • Can open associated file for:
      • Writing
      • Appending

Closing a Stream Object

  • Closed using close() method:
    • Closes the basic I/O stream object and all processing streams created from it

Buffering

  • Every time a byte or sequence of bytes is written

to or read from a file:

  • Call to the underlying operating system is required
  • Resulting operating system calls can be significantly reduced by buffering - Used for almost all file transfers
  • Buffered stream
  • Provides a storage area that is used by data as they are transferred between a program and a file

Reading and Writing

Character-Based Files

  • Similar to reading input from a keyboard and

writing data to a display screen

  • FileWriter stream object:
    • Used for writing to a character-based file
    • Only provides capability to write a character at a time
    • Normally wrapped in another stream object
      • Provides additional processing

Writing to a Character File

  • Setting up FileWriter:
    • FileWriter fw = new FileWriter("prices.txt");
  • Adding buffering for faster output:
    • BufferedWriter bw = new BufferedWriter(fw);
  • Adding additional functionality:
    • PrintWriter pw = new PrintWriter(bw);
    • Use methods:
      • print()
      • println()

Embedded and Interactive File

Names

  • Assign the file name to a string variable at the top

of the program

  • Interactive file name:
    • Prompt the user for a file name
    • Assign to a string variable