0% found this document useful (0 votes)
35 views

CH 4 Java Streams and File I O

Uploaded by

gadisakarorsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

CH 4 Java Streams and File I O

Uploaded by

gadisakarorsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Chapter 4

Java Streams and File I/O

5/5/2023 1
Introduction

• Most real applications of Java are not text-based, console programs.

• Java’s support for console I/O is limited.

• Text-based console I/O is not very important to Java programming.

• Java does provide strong, flexible support for I/O as it relates to files
and networks.

5/5/2023 2
Stream
◼ The Java Input/Output (I/O) is a part of java.io package.
◼ The java.io package contains a relatively large number of classes that support
input and output operations.
◼ The classes in the package are primarily abstract classes and stream-oriented
that define methods and subclasses which allow bytes to be read from and
written to files or other input and output sources.
◼ For reading the stream:
➢ Open the stream
➢ Read information
➢ Close the stream
◼ For writing in stream:
➢ Open the stream
➢ Write information
➢ Close the stream
3
Stream
(continued)
◼ There are two types of stream are:
▪ Byte stream
▪ Character stream
I. Byte Streams:
◼ It supports 8-bit input and output operations. There are two classes of byte stream
◼ InputStream
◼ OutputStream
◼ InputStream:
◼ The InputStream class is used for reading the data such as a byte and array of bytes from an input source.
◼ An input source can be a file, a string, or memory that may contain the data.
◼ It is an abstract class that defines the programming interface for all input streams that are inherited from
it.
◼ An input stream is automatically opened when you create it.
◼ You can explicitly close a stream with the close( ) method, or let it be closed implicitly when the object
is found as a garbage.
4
Stream
(continued)

◼ The subclasses inherited from the InputStream class can be seen in a


hierarchy manner:-
◼ ByteArrayInputStream
◼ FileInputStream
◼ ObjectInputStream
◼ FilterInputStream
◼ PipedInputStream
◼ StringBufferInputStream
◼ FilterInputStream
◼ BufferedInputStream
◼ DataInputStream
◼ LineNumberInputStream
◼ PushbackInputStream

5
Stream
(continued)
◼ OutputStream:
◼ The OutputStream class is a sibling to InputStream that is used for writing
byte and array of bytes to an output source.
◼ Similar to input sources, an output source can be anything such as a file, a
string, or memory containing the data.
◼ Like an input stream, an output stream is automatically opened when you
create it.
◼ You can explicitly close an output stream with the close( ) method, or let it
be closed implicitly when the object is garbage collected.

6
Stream
(continued)
◼ The classes inherited from the OutputStream class can be seen in a hierarchy structure:
◼ OutputStream
◼ ByteArrayOutputStream
◼ FileOutputStream
◼ ObjectOutputStream
◼ FilterInputStream
◼ PipedOutputStream
◼ StringBufferInputStream
◼ FilterOutputStream
◼ BufferedOutputStream

◼ DataOutputStream

◼ PrintStream

◼ OutputStream is also inherited from the Object class. Each class of the OutputStream
provided by the java.io package is intended for a different purpose.
7
Stream
(continued)
◼ Character Streams:
◼ It supports 16-bit Unicode character input and output. There are two classes of character stream
are:-
◼ Reader
◼ Writer
◼ These classes allow internationalization of Java I/O and also allow text to be stored using
international character encoding.
Reader:
Writer:
▪ BufferedReader
▪ BufferedWriter
▪ LineNumberReader
▪ CharAraayWriter
▪ CharAraayReader
▪ FileWriter
▪ PipedReader
▪ PipedWriter
▪ StringReader
▪ PrintWriter
▪ FilterReader
▪ String Writer
▪ PushbackReader
▪ OutputStreamWriter
▪ InputStreamReader
▪ FileWriter
▪ FileReader 8
Standard Streams:
◼ Standard Streams are a feature provided by many operating systems.
◼ By default, they read input from the keyboard and write output to the display.
They also support I/O operations on files.
✓ Standard Input: - Accessed through System.in which is used to read input from the
keyboard.
✓ Standard Output: - Accessed through System.out which is used to write output to be
display.
✓ Standard Error: - Accessed through System.err which is used to write error output to
be display.
◼ Standard Output and Standard Error, both are to write output; having error
output separately so that the user may read error messages efficiently.
◼ System.in is a byte stream that has no character stream features.
◼ To use Standard Input as a character stream, wrap System.in within the
InputStreamReader as an argument.
InputStreamReader inp= new InputStreamReader (System.in);
9
◼ InputStreamReader:
◼ An InputStreamReader is a bridge from byte streams to character streams i.e. it reads bytes and decodes them
into Unicode characters according to a particular platform.
◼ It reads characters from a byte input stream.
◼ When you create an InputStreamReader, you specify an InputStream from which, the InputStreamReader reads
the bytes.
◼ The syntax of InputStreamReader is written as:
◼ InputStreamReader<variable_name>= new InputStreamReader (System.in)
◼ BufferedReader:
◼ The BufferedReader class is the subclass of the Reader class.
◼ It reads character-input stream data from a memory area known as a buffer maintains state.
◼ The buffer size may be specified, or the default size may be used that is large enough for text reading purposes.
◼ BufferedReader converts an unbuffered stream into a buffered stream using the wrapping expression, where the
unbuffered stream object is passed to the constructor for a buffered stream class.
◼ For example the constructors of the BufferedReader class shown as:
◼ BufferedReader (Reader in): Creates a buffering character-input stream that uses a default_x0002_sized input
buffer.
◼ BufferedReader (Reader in, int sz): Creates a buffering character-input stream that uses an input buffer of the
specified size.
10
◼ BufferedReader class provides some standard methods to perform
specific reading operations shown in the table. All methods throw
an IOException, if an I/O error occurs.

11
◼ This program illustrates use of standard input stream to read the user
input.
import java.io.*;
public class ReadStandardIO
{
public static void main(String[] args) throws IOException
{
InputStreamReader inp = new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(inp);
System.out.println("Enter text : ");
String str = br.readLine();
System.out.println("You entered String : ");
System.out.println(str);
}
}
12
File
◼ The File class deals with the machine dependent files in a machine-
independent manner i.e.
◼ It is easier to write platform-independent code that examines and manipulates files using
the File class.
◼ The java.io.File is the central class that works with files and directories.
◼ The instance of this class represents the name of a file or directory on the
host file system.
◼ When a File object is created, the system doesn't check to the existence of
a corresponding file/directory.
◼ If the files exist, a program can examine its attributes and perform various
operations on the file, such as renaming it, deleting it, reading from or
writing to it.
13
◼ The constructors of the File class are:
Constructor Description

File(path) Create File object for default directory (usually where program is
located).

File(dirpath,fname) Create File object for directory path given as string.

File(dir, fname) Create File object for directory.

◼ Thus the statement can be written as:


◼ File f = new File (“<filename>”);
14
◼ The methods that are used with the file object to get the attribute of a corresponding file:
Method Description

f.exists() Returns true if file exists.


f.isFile() Returns true if this is a normal file.
f.isDirectory() true if "f" is a directory.
f.getName() Returns name of the file or directory.
f.isHidden() Returns true if file is hidden.
f.lastModified() Returns time of last modification.
f.length() Returns number of bytes in file.
f.getPath() Path name.
f.delete() Deletes the file.
f.renameTo(f2) Renames f to File f2. Returns true if successful.
f.createNewFile() Creates a file and may throw IOException. 15
◼ Whenever the data is needed to be stored, a file is used to store the
data.
◼ File is a collection of stored information that is arranged in string,
rows, columns and lines etc.
◼ For creating a new file File.createNewFile ( ) method is used; This
method returns a boolean value true if the file is created otherwise
return false.
◼ If the mentioned file for the specified directory is already exist then
the createNewFile () method returns the false otherwise the method
creates the mentioned file and return true.
16
Example that checks the existence of a specified file
import java.io.*;
public class CreateFile1
{
public static void main(String[ ] args) throws IOException
{
File f = new File ("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file \"myfile.txt\" has been created to the
current directory");
}
}
}
17
Example to create a file to the specified location.
import java.io.*;
public class PathFile
{
public static void main(String[] args) throws IOException
{
File f;
f=new File ("example" + File.separator + "myfile.txt");
f.createNewFile ();
System.out.println ("New file \"myfile.txt\" has been created to the specified
location"); System.out.println ("The absolute path of the file is: " +
f.getAbsolutePath ());
}
}
18
I/O Streams
◼ Some I/O streams that are used to perform reading and writing operation in a
file:
✓ FileInputstream
✓ FileOutputStream
◼ FileInputstream:
◼ It is a subclass of Inputstream class that reads bytes from a specified file name.
◼ The read () method of this class reads a byte or array of bytes from the file.
◼ It returns -1 when the end-of-file has been reached.
◼ To read text data, this class is used with an InputStreamReader and BufferedReader
class.
◼ It throws FileNotFoundException, if the specified file is not exist.
◼ FileInputstream (File filename);

19
◼ FileOutputStream:-
◼ It is a subclass of OutputStream that writes data to a specified file name.
◼ The write () method of this class writes a byte or array of bytes to the file.
◼ To write text, we typically use it with a PrintWriter, BufferedWriter and an
OutputStreamWriter class.
◼ FileOutputstream (File filename);
◼ DataInputStream:-
◼ Is a type of FilterInputStream that allows you to read binary data of Java primitive
data types in a portable way.
◼ In other words, the DataInputStream class is used to read binary Java primitive data
types in a machine-independent way.
◼ An application uses a DataOutputStream to write data that can later be read by a
DataInputStream.
◼ DataInputStream (FileOutputstream finp); 20
Example: How contents are read from a file
else{
import java.io.*;
FileInputStream finp=new
public class ReadFile
FileInputStream(f);
{
byte b;
public static void main(String[] args) throws
do{
IOException
b=(byte)finp.read();
{
System.out.print((char)b);
File f;
}
f=new File("myfile.txt");
while(b!=-1);
if(!f.exists()&& f.length()<0)
finp.close();
System.out.println("The specified file is not exist");
}
}
21
◼ If the file exists, the data is written to the file
through the object of the FileOutputStream class.
import java.io.*; String str="This data is written through the
public class WriteFile program";
fop.write (str.getBytes ());
{
fop.flush ();
public static void main(String[] args) throws
IOException fop.close ();
{ System.out.println ("The data has been
written");
File f=new File ("textfile1.txt");
}
FileOutputStream fop=new FileOutputStream (f);
else
if (f.exists ()) System.out.println ("This file is not exist");
{ }

22
Finding a File
◼ To find a file or directory it is very necessary to know the path of the file or
directory so that you can access it. If you know the path then it is very easy to
work on it.
◼ Suppose a situation where a problem comes in front you where you don't know the path
of the file, then what will you do?
◼ This problem can be solved by using a method getAbsolutePath ().

◼ The method getAbsolutePath () should be used where we don't know the exact path of the file.
◼ In this class we have make use of the following things by which this problem
can be solved.
◼ File: It is class in java.io package. It implements Comparable and Serializable
interface.
◼ getAbsolutePath (): It returns the absolute path name in the form of string.
23
Example:
• String absolutePathOfSecondFile =
◼ import java.io.*;
file.getAbsolutePath();
◼ public class GetAbsolutePath
• System.out.println(" The absolute path is " +
◼ { absolutePathOfSecondFile);
◼ public static void main(String[] args) • file = new File("Happy" + File.separator + ".."
◼ { + File.separator+ str);
◼ String str = args[0]; • String absolutePathOfThirdFile =
◼ File file = new File(str); file.getAbsolutePath ();
◼ String absolutePathOfFirstFile = file.getAbsolutePath(); • System.out.println (" The absolute path is” +
◼ System.out.println(" The absolute path in first form is " absolutePathOfThirdFile);
◼ + absolutePathOfFirstFile); • }
◼ file = new File( "Happy" + File.separatorChar+ str);

24
Exercise
Write a program which prompts the user to enter the path of the file to be read (f1)
and file to be written(f2).
Append the content of the file f1 at the end of file f2.

5/5/2023 25

You might also like