Chapter 5 Streams and File IO

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

10/3/2024

Discuss on:
• What are the core reasons we use packages in
programming?
Chapter 5 • What elements typically reside within a package?
Streams and File I/O • What are some of the most common built-in
packages you've encountered in programming?
What specific tasks or functionalities do they
offer?
• What are the primary motivations for using
abstraction in programming?
• What are the key differences and use cases for
abstract classes and interfaces?
1 2

The Java File Class The File Class


• Java File class represents the files and directory pathnames in an
abstract manner.
• The File class is useful for retrieving information about files or
directories from disk.
• The File class contains the methods for obtaining the properties of
a file/directory and for renaming and deleting a file/directory.
• The File class has different methods which can be used to
manipulate the files.
– Absolute path: An absolute file name (or full name) contains a
file name with its complete path and drive letter.
– Relative path: A relative file name is in relation to the current
working directory.

3 4

1
10/3/2024

Example: The File Class Text File and Binary File


This program demonstrates how to create a File object and use the methods in the File class
to obtain its properties. The program creates a File object for the file us.gif. • There are two types of files: Text file or Binary file.
• Data stored in a Text file are represented in human-readable
form.
• Data stored in a binary file are represented in binary form. You
cannot read binary files.
• Binary files are designed to be read by programs.
• For example, the Java source programs are stored in text files and
can be read by a text editor, but the Java .class files are stored in
binary files and are read by the JVM.
• The advantage of binary files I/O are more efficient to process
than text files I/O, because binary file I/O does not require
encoding and decoding. But Text file I/O requires encoding and
decoding.
The lastModified() method returns the date and time when the file was last modified. 5 6

Example 1. Byte I/O Streams


• suppose you write the string "199" using text I/O to a file.

• The ASCII or Unicode 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, as shown in Figure (a) below.

• Binary I/O does not require conversions.

• When you write a byte to a file, the original byte is copied into the file.

• When you read a byte from a file, the exact byte in the file is returned.

• a byte-type value 199 is represented as 0xC7 in the memory and appears 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
exactly as 0xC7 in the file, as shown in Figure (b) below. the host machine and thus are portable. Java programs on any machine can read a
binary file created by a Java program. This is why Java class files are binary files.
Java class files can run on a JVM on any machine.
7 8

2
10/3/2024

Text File Input and Output File Input and Output


• a File object encapsulates the properties of a file or a path but
Scanner input = new Scanner(new File("temp.txt"));
does not contain the methods for reading/writing data from/to System.out.println(input.nextLine());

a file.

• The Scanner class uses for reading text data from a file and
the PrintWriter class uses for writing text data to a file.

• To create an object using Scanner class is:


Scanner input = new Scanner(new File(filename));
PrintWriter output = new PrintWriter("temp.txt");
• To create an object using PrintWriter class is: output.print("Java 101");
PrintWriter output = new PrintWriter(filename); output.close();
9 10

Scanner Class PrintWriter Class

11 12

3
10/3/2024

Example: wring data using PrintWriter Example: reading data using Scanner

13 14

Stream Types I/O Streams


• Java uses the concept of a stream to make I/O operation fast.
– I/O means Input/Output. • Depending upon the type of data flow within the
• The java.io package contains all the classes required for input stream, it (stream) can be classified into:
and output operations.
• A stream can be defined as a sequence of data. 1. Byte I/O Stream
• An I/O Stream is a sequence of data that is read from a source
and write to a destination. 2. Character I/O Stream
• All these streams represent an input source and an output 3. Standard I/O Stream
destination.
input output
• Based on the direction of data flow, it can be
Source
stream
Program
stream
Destination classified into: input and output stream
keyboard or file screen or file
– InputStream and OutputStream (Byte Stream type) or
15 – Reader and Writer (Character Stream type) 16

4
10/3/2024

1. Byte I/O Streams 1. Byte I/O Classes


• It is an input and output data in its binary format.
• Java byte streams are used to perform input and
output of 8-bit bytes.
• All byte stream classes are descended from two
abstract classes: InputStream and OutputStream.
• The InputStream is used to read data from a source
and the OutputStream is used for writing data to a
destination.
• There are many classes related to byte streams but The abstract InputStream is the root class for reading byte data
the most frequently used classes are, and the abstract OutputStream is the root class for writing byte
FileInputStream and FileOutputStream. data.
17 18

InputStream
OutputStream
The value returned is a byte as an int type.

19 20

5
10/3/2024

FileInputStream/FileOutputStream FileInputStream
 To construct a FileInputStream, use the following
constructors:
public FileInputStream(String filename)
public FileInputStream(File file)
 A java.io.FileNotFoundException would occur if you attempt to
create a FileInputStream with a non-existent file.

 FileInputStream/FileOutputStream is for reading/writing bytes from/to files.


 FileInputStream/FileOutputStream associates a binary input/output stream with
an external file.
 All the methods in FileInputStream/FileOuptputStream are inherited from its
superclasses. 21 22

FileOutputStream Example: FileInputStream/FileOutputStream


import java.io.*;
 To construct a FileOutputStream, use the following constructors: public class TestFileStream {
public static void main(String[] args) thorw IOException {
public FileOutputStream(String filename) // Create an output stream to the file
FileOutputStream output = new FileOutputStream("temp.dat");
public FileOutputStream(File file) // Output values to the file
for (int i = 1; i <= 10; i++)
public FileOutputStream(String filename, boolean append) output.write(i);
// Close the output stream
public FileOutputStream(File file, boolean append) output.close();

 If the file does not exist, a new file would be created. // Create an input stream for the file
FileInputStream input = new FileInputStream("temp.dat");
 If the file already exists, the first two constructors would delete the // Read values from the file
int value;
while ((value = input.read() )!= -1)
current contents in the file. System.out.print(value + " "); This program uses binary
I/O to write ten byte
 To retain the current content and append new data into the file, use the // Close the output stream values from 1 to 10 to a
input.close();
file named temp.dat and
last two constructors by passing true to the append parameter. }
} reads them back from
23 the file. 24

6
10/3/2024

FilterInputStream/FilterOutputStream FilterInputStream/FilterOutputStream
• Filter streams are streams that filter bytes for some purpose.
• The basic byte input stream provides a read method that can only be
used 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.

25 26

DataInputStream/DataOutputStream DataInputStream
DataInputStream reads bytes from the stream and
converts them into appropriate primitive type values
or strings. • DataInputStream extends FilterInputStream and implements
the DataInput interface.

DataOutputStream converts primitive type values or


strings into bytes and output the bytes to the stream.
27 28

7
10/3/2024

DataOutputStream Characters and Strings in Byte I/O


• DataOutputStream extends FilterOutputStream and implements • A Unicode consists of two bytes.
the DataOutput interface.
• The writeChar(char c) method writes the Unicode of character c to
the output.
• The writeChars(String s) method writes the Unicode for each
character in the string s to the output.
• The writeBytes(String s) method writes the lower byte of the
Unicode for each character in the string s to the output. The high
byte of the Unicode is discarded.
• The writeBytes method is suitable for strings that consist of ASCII
characters, since an ASCII code is stored only in the lower byte of
a Unicode. If a string consists of non-ASCII characters, you have
to use the writeChars method to write the string.

29 30

Characters and Strings in Byte I/O DataInputStream/DataOutputStream


Why UTF-8? What is UTF-8? • Data streams are used as wrappers on existing input and output streams to
• The writeUTF(String s) method writes two bytes of length information filter data in the original stream. They are created using the following
to the output stream, followed by the modified UTF-8 representation of
every character in the string s. constructors:
• UTF-8 is a coding scheme that allows systems to operate with both public DataInputStream(InputStream instream)
ASCII and Unicode efficiently.
public DataOutputStream(OutputStream outstream)
• Most operating systems use ASCII. Java uses Unicode. The ASCII
character set is a subset of the Unicode character set. • The statements given below create data streams. The first statement
• Since most applications need only the ASCII character set, it is a waste creates an input stream for file in.dat; the second statement creates an
to represent an 8-bit ASCII character as a 16-bit Unicode character.
output stream for file out.dat.
• The UTF is an alternative scheme that stores a character using 1, 2, or 3
bytes. DataInputStream infile = new DataInputStream(new FileInputStream("in.dat"));
• ASCII values (less than 0x7F) are coded in one byte. Unicode values DataOutputStream outfile = new DataOutputStream(new
less than 0x7FFF are coded in two bytes. Other Unicode values are
coded in three bytes. FileOutputStream("out.dat"));
31 32

8
10/3/2024

Example: DataInputStream/DataOutputStream
import java.io.*; Order and Format
public class TestDataStream {
public static void main(String[] args) throws IOException {
// Create an output stream for file temp.dat
DataOutputStream output = new DataOutputStream(new
CAUTION: You have to read the data in the same order and
FileOutputStream("temp.dat")); same format in which they are stored. For example, since
// Write student test scores to the file
output.writeUTF("John"); names are written in UTF-8 using writeUTF, you must read
output.writeDouble(85.5); This program writes student names using readUTF.
output.writeUTF("Susan"); names and scores to a file
output.writeDouble(185.5); named temp.dat and reads the
output.writeUTF("Kim");
output.writeDouble(105.25);
// Close output stream
data back from the file.
Checking End of File
output.close();
// Create an input stream for file temp.dat
DataInputStream input = new DataInputStream(new TIP: If you keep reading data at the end of a stream, an
FileInputStream("temp.dat"));
EOFException would occur. So how do you check the end
// Read student test scores from the file
System.out.println(input.readUTF()+ " " + input.readDouble());
of a file? You can use input.available() to check it.
System.out.println(input.readUTF() + " " + input.readDouble()); input.available() == 0 indicates that it is the end of a file.
System.out.println(input.readUTF() + " " + input.readDouble());
}
} 33 34

BufferedInputStream/BufferedOutputStream 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, as
shown in Figure (a) below.

• Using BufferedOutputStream, the individual data are first written to the


buffer in the memory.
BufferedInputStream/BufferedOutputStream does not contain new methods. • When the buffer is full, all data in the buffer is written to the disk once, as
All the methods BufferedInputStream/BufferedOutputStream are inherited from the
InputStream/OutputStream classes. BufferedInputStream/BufferedOutputStream shown in Figure (b) below.
manages a buffer behind the scene and automatically reads/writes data from/to disk
35 36
on demand.

9
10/3/2024

Constructing
BufferedInputStream/BufferedOutputStream
BufferedInputStream/BufferedOutputStream
// Create a BufferedInputStream
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int bufferSize)
// Create a BufferedOutputStream
public BufferedOutputStream(OutputStream out)
public BufferedOutputStream(OutputStreamr out, int bufferSize)

• If no buffer size is specified, the default size is 512 bytes.

37 38

BufferedInputStream/BufferedOutputStream 2. Character I/O Streams


• Character Stream is an input and output data as a
sequence of characters.
DataInputStream input = new DataInputStream(new
• Java Byte streams are used to perform input and
BufferedInputStream(new FileInputStream("temp.dat")));
output of 8-bit bytes, whereas Java Character
streams are used to perform input and output for
DataOutputStream output = new DataOutputStream(new 16-bit Unicode.
BufferedOutputStream (new FileOutputStream("temp.dat"))); • All character stream classes are also descended
from two abstract classes Read and Writer.
• The most frequently used character stream classes
are: FileReader and FileWriter.
39 40

10
10/3/2024

2. Character I/O Streams 3. Standard I/O Streams


• All the programming languages provide support for
standard I/O where the user's program can take input from
a keyboard and then produce an output on the computer
screen.
• Java provides the following three standard streams:
– Standard Input - This is used to feed the data to user's
program and usually a keyboard is used as standard input
stream and represented as System.in.
– Standard Output - This is used to output the data produced by
the user’s program and usually a computer screen is used for
standard output stream and represented as System.out.
– Standard Error - This is used to output the error data
produced by the user’s program and usually a computer screen
is used for standard error stream and represented as
System.err.
41 42

Read more on:


• Sub classes of other inputStream / outputStream
(e.g. ObjectInputStream/ObjectOutputStream
class)
• Sub classes of Reader and Writer Class
• Random access file The End!!

43 44

11

You might also like