0% found this document useful (0 votes)
36 views8 pages

Chapter 2 - 1: Streams and File I/O

This document provides an overview of file input/output (I/O) in Java. It discusses the differences between text and binary files, and describes the core I/O classes in Java for reading and writing both types of files. Key classes include PrintWriter and Scanner for text I/O, and InputStream, OutputStream, FileInputStream, FileOutputStream, DataInputStream and DataOutputStream for binary I/O. The document explains how to create I/O streams and use methods like read(), write() to access file contents.

Uploaded by

biruk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
36 views8 pages

Chapter 2 - 1: Streams and File I/O

This document provides an overview of file input/output (I/O) in Java. It discusses the differences between text and binary files, and describes the core I/O classes in Java for reading and writing both types of files. Key classes include PrintWriter and Scanner for text I/O, and InputStream, OutputStream, FileInputStream, FileOutputStream, DataInputStream and DataOutputStream for binary I/O. The document explains how to create I/O streams and use methods like read(), write() to access file contents.

Uploaded by

biruk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 8

Chapter 2 – 1

Streams and File I/O


Introduction

Java provides many classes for performing text I/O and binary I/O. Files can be classified as
either text or binary. A file that can be processed (read, created, or modified) using a text editor
such as Notepad is called a text file. All the other files are called binary files. You cannot read
binary files using a text editor—they are designed to be read by programs. For example, Java
source programs are stored in text files and can be read by a text editor, but Java class files are
stored in binary files and are read by the JVM.

Characters in a text file are encoded using a character encoding scheme such as ASCII or
Unicode. For example, the decimal integer 199 is stored as the sequence of the three characters
1, 9, 9 in a text file, and the same integer is stored as a byte-type value C7 in a binary file,
because decimal 199 equals hex C7 (199 = 12 * 161+ 7). The advantage of binary files is that
they are more efficient to process than text files. Java offers many classes for performing file
input and output. These can be categorized as text I/O classes and binary I/O classes.

How Is Text I/O Handled in Java?

Recall that a File object encapsulates the properties of a file or a path but does not contain the
methods for reading/writing data from/to a file. In order to perform I/O, you need to create
objects using appropriate Java I/O classes. The objects contain the methods for reading/writing
data from/to a file. For example, to write text to a file named temp.txt, you can create an object
using the PrintWriter class as follows:

PrintWriter output = new PrintWriter("temp.txt");

You can now invoke the print method on the object to write a string to the file. For example, the
following statement writes Java 101 to the file. output.print("Java 101");

The next statement closes the file.

output.close();
There are many I/O classes for various purposes. In general, these can be classified as input
classes and output classes. An input class contains the methods to read data, and an output class
contains the methods to write data. PrintWriter is an example of an output class, and Scanner is
an example of an input class. The following code creates an input object for the file temp.txt and
reads data from the file.

Scanner input = new Scanner(new File("temp.txt"));

System.out.println(input.nextLine());

If temp.txt contains the text Java 101, input.nextLine() returns the string "Java 101".

The following figure illustrates Java I/O programming. An input object reads a stream of data
from a file, and an output object writes a stream of data to a file. An input object is also called an
input stream and an output object an output stream.

The program receives data through an input object and sends data through an output object.

Text I/O vs. Binary I/O

Computers do not differentiate between binary files and text files. All files are stored in binary
format, and thus all files are essentially binary files. Text I/O is built upon binary I/O to provide
a level of abstraction for character encoding and decoding. Encoding and decoding are
automatically performed for text I/O. The JVM converts Unicode to a file-specific encoding
when writing a character and it converts a file-specific encoding to Unicode when reading a
character. For example, suppose you write the string "199" using text I/O to a file. Each character
is written to the file. Since the Unicode for character 1 is 0x0031, the Unicode 0x0031 is
converted to a code that depends on the encoding scheme for the file. In the United States, the
default encoding for text files on Windows is ASCII. The ASCII code for character 1 is 49 (0x31
in hex) and for character 9 is 57 (0x39 in hex). Thus, to write the characters 199, three bytes—

0x31, 0x39, and 0x39—are sent to the output. Binary I/O does not require conversions. If you
write a numeric value to a file using binary I/O, the exact value in the memory is copied into the
file. For example, a byte-type value 199 is represented as 0xC7 in the memory and appears
exactly as 0xC7 in the file, as shown in Figure 19.2b. When you read a byte using binary I/O,
one byte value is read from the input.

In general, you should use text input to read a file created by a text editor or a text output
program, and use binary input to read a file created by a Java binary output program. Binary I/O
is more efficient than text I/O, because binary I/O does not require encoding and decoding.
Binary files are independent of the encoding scheme on the host machine and thus are portable.

Binary I/O Classes

The abstract InputStream is the root class for reading binary data and the abstract OutputStream
is the root class for writing binary data. The following figure lists some of the classes for
performing binary I/O. InputStream is the root for binary input classes, and OutputStream is the
root for binary output classes.

Fig. InputStream, OutputStream, and their subclasses are for performing binary I/O.
Fig. the abstract InputStream class defines the methods for the input stream of bytes.

Fig The abstract OutputStream class defines the methods for the output stream of bytes.

FileInputStream/FileOutputStream

FileInputStream/FileOutputStream is for reading/writing bytes from/to files. All the methods in


these classes are inherited from InputStream and OutputStream.
FileInputStream/FileOutputStream does not introduce new methods.

A java.io.FileNotFoundException will occur if you attempt to create a FileInputStream with a


nonexistent file.

Table: - constructors of file IO classes

FileInpuStream constructors
Constructor name Description
+FileInpuStream(file: File) a FileInputStream from a File object
FileInputStream(fileName: String) - creates a FileInputStream from a file name

FileOutputStream Constructors
+FileOutputStream(file: File) Creates a FileOutputStream from a File object.
+FileOutputStream(filename: String) Creates a FileOutputStream from a file name.
+FileOutputStream(file: File, append: boolean) If append is true, data are appended to the
existing file.
+FileOutputStream(filename: String, append: If append is true, data are appended to the
boolean) existing file.

import java.io.*;
class IODemo {
public static void main (String [] s)throws IOException{
FileOutputStream fout = new FileOutputStream("byte.dat");
for (int i = 0; i <= 10; i++)
{
System.out.println("Writing " + i);
fout.write(i);
}
fout.close();
FileInputStream fin = new FileInputStream("byte.dat");
int i;
while((i = fin.read()) != -1){
System.out.print(i + " ");
}
fin.close(); } }
A FileOutputStream is created for the file byte.dat. The for loop writes ten byte values into the
file. Invoking write (i) is the same as invoking write((byte)i). FileInputStream is created for the
file byte.dat. Values are read from the file and displayed on the console in lines. The expression
((value = input.read()) != -1) reads a byte from input.read(), assigns it to value, and checks
whether it is –1. The input value of –1 signifies the end of a file. The file byte.dat created in this
example is a binary file. It can be read from a Java program but not from a text editor.
FilterInputStream/FilterOutputStream
Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides
a read method that can be used only for reading bytes. If you want to read integers, doubles, or
strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to
read integers, doubles, and strings instead of bytes and characters.
FilterInputStream and FilterOutputStream are the base classes for filtering data.
When you need to process primitive numeric types, use DataInputStream and DataOutputStream
to filter bytes.
DataInputStream/DataOutputStream
DataInputStream reads bytes from the stream and converts them into appropriate primitive type
values or strings. DataOutputStream converts primitive type values or strings into bytes and
outputs the bytes to the stream.
DataInputStream extends FilterInputStream and implements the DataInput interface.
DataOutputStream extends FilterOutputStream and implements the DataOutput interface.
Creating DataInputStream/DataOutputStream
DataInputStream/DataOutputStream are created using the following constructors
public DataInputStream(InputStream instream)
public DataOutputStream(OutputStream outstream)
The following statements create data streams. The first statement creates an input stream for the
file in.dat; the second statement creates an output stream for the file out.dat.
DataInputStream input =(new FileInputStream("in.dat"));
DataOutputStream output =(new FileOutputStream("out.dat"));
The following program writes student names and scores to a file named temp.dat and reads the
data back from the file.
import java.io.*;
public class TestDataStream {
public static void main(String[] args) throws IOException {
// Create an output stream for file temp.dat
new DataOutputStream(new FileOutputStream("temp.dat"));
DataOutputStream output = new DataOutputStream(new FileOutputStream("temp.dat"));
output.writeUTF("John");
output.writeDouble(85.5);
output.writeUTF("Susan");
output.writeDouble(185.5);
output.writeUTF("Kim");
output.writeDouble(105.25);
output.close();
DataInputStream input = new DataInputStream(new FileInputStream("temp.dat"));
System.out.println (input.readUTF() + " " + input.readDouble());
System.out.println(input.readUTF() + " " + input.readDouble());
System.out.println(input.readUTF() + " " + input.readDouble());
} }
A DataOutputStream is created for file temp.dat. Student names and scores are written to the file.
A DataInputStream is created for the same file. Student names and scores are read back from the
file and displayed on the console.
DataInputStream and DataOutputStream read and write Java primitive type values and strings in
a machine-independent fashion, thereby enabling you to write a data file on one machine and
read it on another machine that has a different operating system or file structure.
An application uses a data output stream to write data that can later be read by a program using a
data input stream.
BufferedInputStream/BufferedOutputStream
BufferedInputStream/BufferedOutputStream can be used to speed up input and output by
reducing the number of disk reads and writes. Using BufferedInputStream, the whole block of
data on the disk is read into the buffer in the memory once. The individual data are then
delivered to your program from the buffer. Using BufferedOutputStream, the individual data are
first written to the buffer in the memory. When the buffer is full, all data in the buffer is written
to the disk once.

Buffer I/O places data in a buffer for fast processing.


BufferedInputStream/BufferedOutputStream does not contain new methods. All the methods in
BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream
classes. BufferedInputStream/BufferedOutputStream manages a buffer behind the scene and
automatically reads/writes data from/to disk on demand. You can wrap a
BufferedInputStream/BufferedOutputStream on any InputStream/OutputStream using the
constructors.
If no buffer size is specified, the default size is 512 bytes. You can improve the performance of
the TestDataStream program by adding buffers in the stream.
DataOutputStream output = new DataOutputStream(new BufferedOutputStream
(new FileOutputStream("temp.dat")));
DataInputStream input = new DataInputStream(new BufferedInputStream(new
FileInputStream("temp.dat")));

You might also like