Introduction to file input and output

Two types of files:

Constructors Description
Text A file that contains characters. The fields are records in this type of file are often deliited by special characters like tab and new lines chars.
Binaray A file that may contain characters as well as other non-character data types that can't be read by a text editor.

Two types of streams:

Method Description
Character Used to transfer text data to or from an I/O device.
Binary Used to transfer binary data to or from an I/O device.

Descriptions:

  • An input file is a file that is read by a program; an output file is a file that is written by a program. Input and output operations are often referred to as I/O operations or file I/O.
  • A stream is the flow of data from one location to another. To write data to a file from internal storage, you use an output stream. To read from a file into internal storage, you use an input stream.
  • To read and write text files, you use character streams. To read and write binary files, you use binary streams.
  • Streams are not only used with disk devices, but also with input devices like keyboards and networks connections and output devices like PC monitors and network connections.

Example 1 : Import all classes in the java.io package

import java.io.*;

Example 2 : Create a File object

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

Example 3 : Write data to the stream

PrintWriter out = new PrintWriter(
new BufferedWriter(
New FileWriter(productsFile)));
out.println("java\tData");
out.close();

Example 4 : Read data to the stream

BufferedReader in = new BufferedReader(
new FileReader(productsFile));
String line = in.readLine();
out.close();