CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Files

Text and Binary Files
File input and output
File I/O

Handling file I/O

  • The java.io package contains dozens of classes that can be used to create different types of streams that have different functionality.
  • The java.nio package contains even more classes for working with I/O.
  • To get the functionality you need for a stream, you often need to combine, or layer, two or more streams.
  • To make disk processing more efficient, you can use a buffered stream that adds a block of internal memory called a buffer to the stream.
  • When working with buffers, you often need to flush the buffer. This sends all data in the buffer to the I/O device. One way to do that is to close the I/O stream.

Import all classes in the java.io package

import java.io.*;

Create a File object

File productsFile = new File("products.txt");

Write data to the file

Step 1: Open a buffered output stream

PrintWriter out = new PrintWriter(
                  new BufferedWriter(
                  new FileWriter(productsFile)));

Step 2: Write data to the stream

out.println("java\tMurach's Beginning Java 2\t49.50");

Step 3: Close the stream and flush all data to the file

out.close();

Read data from the file

Step 1: Open a buffered input stream

BufferedReader in = new BufferedReader(
                    new FileReader(productsFile));

Step 2: Read data from the stream and print it to the console

String line = in.readLine();
System.out.println(line);

Step 3: Close the stream

out.close();

Resulting output

java  Murach's Beginning Java 2  49.50
Previous | Files and streams | File I/O | I/O exceptions | Next