0% found this document useful (0 votes)
8 views84 pages

Chapter 11 - Streams and File IO

The document discusses Java I/O Streams, explaining the concepts of input and output streams, and categorizing them into Byte Streams, Character Streams, Buffered Streams, and Data Streams. It details the InputStream and OutputStream classes, their subclasses like FileInputStream and FileOutputStream, and their methods for reading and writing data. Additionally, it covers the Reader class and InputStreamReader for character-based I/O operations, emphasizing the importance of character encoding.

Uploaded by

Adamu Tiruneh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views84 pages

Chapter 11 - Streams and File IO

The document discusses Java I/O Streams, explaining the concepts of input and output streams, and categorizing them into Byte Streams, Character Streams, Buffered Streams, and Data Streams. It details the InputStream and OutputStream classes, their subclasses like FileInputStream and FileOutputStream, and their methods for reading and writing data. Additionally, it covers the Reader class and InputStreamReader for character-based I/O operations, emphasizing the importance of character encoding.

Uploaded by

Adamu Tiruneh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Modern Programming

Practices with Java

Instructor: Solomon (Ph.D)


Chapter 11: Streams and File I/O
Java I/O Streams
• In Java, streams are the sequence of data that are read
from the source and written to the destination.
• An input stream is used to read data from the source.
And, an output stream is used to write data to the
destination. For example,
public class Main {
public static void main(String[] args) {
[Link]("Hello World!");
}
}

− In the example, we have used [Link] to print a string.


Here, the [Link] is a type of output stream.
− Similarly, there are input streams, such as [Link], which are
used to take input from the user (e.g., from the keyboard).
Types of Streams
• Depending upon the data a stream holds, it can be
classified into Byte Stream, Character Stream, Buffered
Streams and Data Streams.
1) Byte Streams:
– Designed to handle raw binary data.
– Use InputStream for reading and OutputStream for
writing.
– Example: Reading or writing images, videos, or binary files.
2) Character Streams:
– Designed to handle text data (character-based I/O).
– Use Reader for reading and Writer for writing.
– Example: Reading and writing text files.
Types of Streams …
3) Buffered Streams:
– Add buffering to improve efficiency by reducing the number of
I/O operations.
– Examples: BufferedReader and BufferedWriter.
4) Data Streams:
– Handle primitive data types (e.g., int, float) and strings in a
machine-independent way.
– Examples: DataInputStream and DataOutputStream.
Byte Streams
InputStream Class
• The InputStream class of the [Link] package is an
abstract superclass that represents an input stream of
bytes.
• Since InputStream is an abstract class, it is not useful
by itself. However, its subclasses can be used to read
data.
• Subclasses of InputStream:
– In order to use the functionality of InputStream, we can use
its subclasses. Some of them are:
▪ FileInputStream: Reads bytes from a file.
▪ BufferedInputStream: Adds buffering to improve
performance.
▪ DataInputStream: Reads primitive data types and strings.
Create an InputStream
• In order to create an InputStream, we must import the
[Link] package first. Once we import
the package, here is how we can create the input stream.
// Creates an InputStream
InputStream obj = new FileInputStream();
• Here, we have created an input stream using
FileInputStream. It is because InputStream is an
abstract class. Hence, we cannot create an object of
InputStream.
• Note: We can also create an input stream from other
subclasses of InputStream.
Methods of InputStream
• The InputStream class provides different methods
that are implemented by its subclasses. Here are some of
the commonly used methods:
– read() - reads one byte of data from the input stream.
– read(byte[] array) - reads bytes from the stream and stores in
the specified array.
– available() - returns the number of bytes available in the input
stream.
– mark() - marks the position in the input stream up to which data has
been read.
– reset() - returns the control to the point in the stream where the
mark was set.
– skips() - skips and discards the specified number of bytes from the
input stream.
– close() - closes the input stream.
– …
FileInputStream Class
• The FileInputStream class of the [Link] package
can be used to read data (in bytes) from files.
• It extends the InputStream abstract class.

• Create a FileInputStream:
– In order to create a file input stream, we must import the
[Link] package first. Once we import
the package, here is how we can create a file input stream in Java.
1. Using the path to file
FileInputStream input = new FileInputStream(stringPath);
− Here, we have created an input stream that will be linked to the file
specified by the path.
FileInputStream Class …
2. Using an object of the file
FileInputStream input = new FileInputStream(File fileObject);
− Here, we have created an input stream that will be linked to the file
specified by fileObject.
▪ Methods of FileInputStream
– The FileInputStream class provides implementations for
different methods present in the InputStream class.
➢ read() Method:
– read() - reads a single byte from the file.
– read(byte[] array) - reads the bytes from the file and
stores in the specified array.
– read(byte[] array, int start, int length) -
reads the number of bytes equal to length from the file and stores
in the specified array starting from the position start.
– …
FileInputStream Class …
• Let’s try to read [Link] using FileInputStream.
import [Link];

public class Main {


public static void main(String args[]) {
File fileObj = new File("[Link]"); // Create a File object
try {
// String filePath = “[Link]";
FileInputStream input = new FileInputStream(fileObj); // filePath
[Link]("Data in the file: ");
int i = [Link](); // Reads the first byte
while(i != -1) {
[Link]((char)i);
i = [Link](); // Reads next byte from the file
}
[Link]();
}
catch(Exception e) {}
}
}
Output:
Data in the file: This is a line of text inside the file.

• To read data from the file, we have used the read() method inside
the while loop.
FileInputStream Class …
➢ available() Method:
– To get the number of available bytes, we can use the
available() method. For example,
import [Link];

Public class Main {


public static void main(String args[]) {
try {
// Suppose, the [Link] file contains the following text
// This is a line of text inside the file.
FileInputStream input = new FileInputStream("[Link]");
// Returns the number of available bytes
[Link]("Available bytes at the beginning: " + [Link]());
// Reads 3 bytes from the file
[Link]();
[Link]();
[Link]();
// Returns the number of available bytes
[Link]("Available bytes at the end: " + [Link]());
[Link]();
}
catch (Exception e) {}
} Output:
} Available bytes at the beginning: 39
Available bytes at the end: 36
FileInputStream Class …
➢ skip() Method:
– To discard and skip the specified number of bytes, we can use the
skip() method. For example,
import [Link];
Public class Main {
public static void main(String args[]) {
try {
// Suppose, the [Link] file contains the following text
// This is a line of text inside the file.
FileInputStream input = new FileInputStream("[Link]");
// Skips the 5 bytes
[Link](5);
[Link]("Input stream after skipping 5 bytes:");
// Reads the first byte
int i = [Link]();
while (i != -1) {
[Link]((char) i);
i = [Link](); // Reads next byte from the file
}
[Link](); // close() method
}
catch (Exception e) {}
} Output:
} Input Stream after skipping 5 bytes:
is a line of text inside the file.
FileInputStream Class …
➢ close() Method:
– To close the file input stream, we can use the close() method.
– Once the close() method is called, we cannot use the input
stream to read data.
OutputStream Class
• The OutputStream class of the [Link] package is an
abstract superclass that represents an output stream of
bytes.
• Since OutputStream is an abstract class, it is not useful
by itself. However, its subclasses can be used to write
data.
• Subclasses of OutputStream:
– In order to use the functionality of OutputStream, we can use
its subclasses. Some of them are:
▪ FileOutputStream: Writes bytes to a file.
▪ BufferedOutputStream: Adds buffering to improve
performance.
▪ DataOutputStream: Writes primitive data types and strings.
Create an OutputStream
• In order to create an OutputStream, we must import
the [Link] package first. Once we
import the package, here is how we can create the output
stream.
// Creates an OutputStream
OutputStream obj = new FileOutputStream();
• Here, we have created an object of output stream using
FileOutputStream. It is because OutputStream is
an abstract class, so we cannot create an object of
OutputStream.
• Note: We can also create the output stream from other
subclasses of the OutputStream class.
Methods of OutputStream
• The OutputStream class provides different methods
that are implemented by its subclasses. Here are some of
the methods:
– write() - writes the specified byte to the output stream.
– write(byte[] array) - writes the bytes from the specified
array to the output stream.
– flush() - forces to write all data present in output stream to
the destination.
– close() - closes the output stream.
– …
FileOutputStream Class
• The FileOutputStream class of the [Link]
package can be used to write data (in bytes) to the files.
• It extends the OutputStream abstract class.

• Create a FileOutputStream:
– In order to create a file output stream, we must import the
[Link] package first. Once we
import the package, here is how we can create a file output
stream in Java.
1. Using the path to file
// Including the boolean parameter
FileOutputStream output = new FileOutputStream(String path, boolean value);
// Not including the boolean parameter
FileOutputStream output = new FileOutputStream(String path);
FileOutputStream Class …
− Here, we have created an output stream that will be linked to the
file specified by the path.
− Also, value is an optional boolean parameter. If it is set to
true, the new data will be appended to the end of the existing
data in the file. Otherwise, the new data overwrites the existing
data in the file.
2. Using an object of the file
FileOutputStream output = new FileOutputStream(File fileObject);
− Here, we have created an output stream that will be linked to the
file specified by fileObject.
▪ Methods of FileOutputStream
– The FileOutputStream class provides implementations for
different methods present in the OutputStream class.
➢ write() Method:
− write() - writes the single byte to the file output stream
FileOutputStream Class …
− write(byte[] array) - writes the bytes from the specified
array to the output stream.
− write(byte[] array, int start, int length) -
writes the number of bytes equal to length to the output stream
from an array starting from the position start.
− …
• Example: FileOutputStream to write data to a File
import [Link];

public class Main {


public static void main(String[] args) {
String data = "This is a line of text inside the file.";
try {
FileOutputStream output = new FileOutputStream("[Link]");
byte[] arr = [Link]();
// Writes byte to the file
[Link](arr);
[Link](); Note: The getBytes() method used
}
catch(Exception e) {}
in the program converts a string into an
} array of bytes.
}
FileOutputStream Class …
➢ flush() Method:
– To clear the output stream, we can use the flush() method.
This method forces the output stream to write all data to the
destination. For example,
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
FileOutputStream out = null;
String data = "This is demo of flush method";
try {
out = new FileOutputStream("[Link]");
[Link]([Link]()); // Using write() method
[Link](); // Using the flush() method
[Link]();
}
catch(Exception e) {}
}
}

− When we run the program, the file [Link] is filled with the text
represented by the string data.
FileOutputStream Class …
➢ close() Method:
– To close the file output stream, we can use the close()
method.
– Once the method is called, we cannot use the methods of
FileOutputStream.
Character Streams
Reader Class
• The Reader class of the [Link] package is an abstract
superclass that represents a stream of characters.
• Since Reader is an abstract class, it is not useful by itself.
However, its subclasses can be used to read data.
• Subclasses of Reader:
– In order to use the functionality of Reader, we can use its
subclasses. Some of them are:
▪ InputStreamReader: Bridges byte streams (InputStream) to
character streams.
▪ FileReader: Reads characters from a file.
▪ BufferedReader: Adds buffering to improve performance and
provides additional methods like readLine().
▪ StringReader: Reads characters from a string.
Reader Class …
• Create a Reader:
– In order to create a Reader, we must import the
[Link] package first. Once we import the package,
here is how we can create the reader.
// Creates a Reader
Reader input = new FileReader();
– Here, we have created a reader using the FileReader class. It
is because Reader is an abstract class. Hence, we cannot create
an object of Reader.
– Note: We can also create readers from other subclasses of
Reader.
▪ Methods of Reader
– The Reader class provides different methods that are
implemented by its subclasses. Here are some of the commonly
used methods:
▪ ready() - checks if the reader is ready to be read.
Reader Class …
▪ read(char[] array) - reads the characters from the stream
and stores in the specified array.
▪ read(char[] array, int start, int length) - reads
the number of characters equal to length from the stream and stores
in the specified array starting from the start.
▪ mark() - marks the position in the stream up to which data has
been read.
▪ reset() - returns the control to the point in the stream where the
mark is set.
▪ skip() - discards the specified number of characters from the
stream.
▪ …
InputStreamReader Class
• The InputStreamReader class of the [Link] package
can be used to convert data in bytes into data in characters. It
extends the abstract class Reader.

• The InputStreamReader class works with other input


streams. It is also known as a bridge between byte streams and
character streams. This is because the
InputStreamReader reads bytes from the input stream as
characters.
• For example, some characters required 2 bytes to be stored in
the storage. To read such data we can use the input stream
reader that reads the 2 bytes together and converts into the
corresponding character.
InputStreamReader Class …
• Create an InputStreamReader:
– In order to create an InputStreamReader, we must import
the [Link] package first. Once we
import the package, here is how we can create the input stream
reader.
// Creates an InputStream
FileInputStream file = new FileInputStream(String path);
// Creates an InputStreamReader
InputStreamReader input = new InputStreamReader(file);
– In the above example, we have created an InputStreamReader
named input along with the FileInputStream named file.
– Here, the data in the file are stored using some default character
encoding. However, we can specify the type of character encoding
(UTF-8 or UTF-16) in the file as well.
// Creates an InputStreamReader specifying the character encoding
InputStreamReader input = new InputStreamReader(file, Charset cs);

− Here, we have used the Charset class to specify the character


encoding in the file.
InputStreamReader Class …
▪ Methods of InputStreamReader
– The InputStreamReader class provides implementations
for different methods present in the Reader class.
➢ read() Method:
− read() - reads a single character from the reader.
− read(char[] array) - reads the characters from the reader and
stores in the specified array.
− read(char[] array, int start, int length) - reads the
number of characters equal to length from the reader and stores in the
specified array starting from the start.
− …
• For example, suppose we have a file named [Link] with
the following content.
This is a line of text inside the file.
• Let's try to read this file using InputStreamReader.
InputStreamReader Class …
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
char[] arr = new char[100]; // Creates an array of character
try {
// Creates a FileInputStream
FileInputStream file = new FileInputStream("[Link]");
// Creates an InputStreamReader
InputStreamReader input = new InputStreamReader(file);
[Link](arr); // Reads characters from the file
[Link]("Data in the stream: ");
[Link](arr);
[Link](); // Closes the reader
}
catch(Exception e) {}
}
Output:
Data in the stream: This is a line of text inside the file.
• To read characters from the file, we have used the read() method.
InputStreamReader Class …
➢ getEncoding() Method:
– The getEncoding() method can be used to get the type of
encoding that is used to store data in the input stream. For
example,
import [Link];
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
try {
// Creates a FileInputStream
FileInputStream file = new FileInputStream("[Link]");
// Creates an InputStreamReader with default encoding
InputStreamReader input1 = new InputStreamReader(file);
// Creates an InputStreamReader specifying the encoding
InputStreamReader input2 = new InputStreamReader(file, [Link]("UTF16"));
// Returns the character encoding of the input stream
[Link]("Character encoding of input1: " + [Link]());
[Link]("Character encoding of input2: " + [Link]());
// Closes the reader
[Link]();
[Link]();
}
catch(Exception e) {}
Output:
} The character encoding of input1: UTF8
} The character encoding of input2: UTF-16
InputStreamReader Class …
• In the above example, we have created 2 input stream
reader named input1 and input2.
– input1 does not specify the character encoding. Hence, the
getEncoding() method returns the name of the default
character encoding (UTF8).
– input2 specifies the character encoding, UTF-16. Hence, the
getEncoding() method returns the specified character
encoding.
• Note: We have used the [Link]() method
to specify the type of character encoding.
➢ close() Method:
– To close the input stream reader, we can use the close()
method.
– Once the close() method is called, we cannot use the reader
to read the data.
FileReader Class
• The FileReader class of the [Link] package can be
used to read data (in characters) from files.
• It extends the InputSreamReader class.

• Create a FileReader:
– In order to create a file reader, we must import the
[Link] package first. Once we import the
package, here is how we can create the file reader.
FileReader Class …
1. Using the name of the file:
FileReader input = new FileReader(String name);
− Here, we have created a file reader that will be linked to the file
specified by the name.
2. Using an object of the file:
FileReader input = new FileReader(File fileObj);
− Here, we have created a file reader that will be linked to the file
specified by the object of the file.
• In the above example, the data in the file are stored using
some default character encoding.
• However, since Java 11 we can specify the type of
character encoding (UTF-8 or UTF-16) in the file as well.
FileReader input = new FileReader(String file, Charset cs);

• Here, we have used the Charset class to specify the


character encoding of the file reader.
FileReader Class …
▪ Methods of FileReader
− The FileReader class provides implementations for different
methods present in the Reader class.
➢ read() Method:
− read() - reads a single character from the reader.
− read(char[] array) - reads the characters from the reader
and stores in the specified array.
− read(char[] array, int start, int length) -
reads the number of characters equal to length from the reader
and stores in the specified array starting from the position start.
− …
• For example, suppose we have a file named [Link] with
the following content.
This is a line of text inside the file.
• Let's try to read the file using FileReader.
FileReader Class …
import [Link];

public class Main {


public static void main(String[] args) {
// Creates an array of character
char[] arr = new char[100];
try {
// Creates a reader using the FileReader
FileReader input = new FileReader("[Link]");
[Link](arr); // Reads characters

[Link]("Data in the file: ");


[Link](arr);
[Link](); // Closes the reader
}
catch(Exception e) {}
}
}
Output:
Data in the file: This is a line of text inside the file.
FileReader Class …
➢ getEncoding() Method:
– The getEncoding() method can be used to get the type of encoding
that is used to store data in the file. For example,
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
try {
// Creates a FileReader with default encoding
FileReader input1 = new FileReader("[Link]");
// Creates a FileReader specifying the encoding
FileReader input2 = new FileReader("[Link]", [Link]("UTF16"));
// Returns the character encoding of the file reader
[Link]("Character encoding of input1: " + [Link]());
[Link]("Character encoding of input2: " + [Link]());
// Closes the reader
[Link]();
[Link]();
} Output:
catch(Exception e) {}
The character encoding of input1: UTF8
}
The character encoding of input2: UTF-16
}
− Note: We have used the [Link]() method to specify the type of character
encoding.
FileReader Class …
➢ close() Method:
– To close the file reader, we can use the close() method.
– Once the close() method is called, we cannot use the reader
to read the data.
Writer Class
• The Writer class of the [Link] package is an abstract
superclass that represents a stream of characters.
• Since Writer is an abstract class, it is not useful by itself.
However, its subclasses can be used to write data.
• Subclasses of Writer:
– In order to use the functionality of the Writer, we can use its
subclasses. Some of them are:
▪ OutputStreamWriter: Bridges byte streams (OutputStream)
to character streams.
▪ FileWriter: Writes characters to a file.
▪ BufferedWriter: Adds buffering to improve performance.
▪ StringWriter: Writes characters to a string buffer.
Writer Class …
• Create a Writer:
− In order to create a Writer, we must import the
[Link] package first. Once we import the package,
here is how we can create the writer.
// Creates a Writer
Writer output = new FileWriter();
– Here, we have created a writer named output using the
FileWriter class. It is because the Writer is an abstract
class. Hence, we cannot create an object of Writer.
– Note: We can also create writers from other subclasses of the
Writer class.
▪ Methods of Writer
– The Writer class provides different methods that are
implemented by its subclasses. Here are some of the methods:
▪ write(char[] array) - writes the characters from the
specified array to the output stream.
Writer Class …
▪ write(String data) - writes the specified string to the writer.
▪ append(char c) - inserts the specified character to the current
writer.
▪ flush() - forces to write all the data present in the writer to the
corresponding destination.
▪ close() - closes the writer.
▪ …
OutputStreamWriter Class
• The OutputStreamWriter class of the [Link] package can
be used to convert data in character form into data in bytes form.
• It extends the abstract class Writer.

• The OutputStreamWriter class works with other output


streams. It is also known as a bridge between byte streams and
character streams. This is because the OutputStreamWriter
converts its characters into bytes.
• For example, some characters require 2 bytes to be stored in the
storage. To write such data we can use the output stream writer that
converts the character into corresponding bytes and stores the bytes
together.
OutputStreamWriter Class …
• Create an OutputStreamWriter:
– In order to create an OutputStreamWriter, we must import the
[Link] package first. Once we import
the package, here is how we can create the output stream writer.
// Creates an OutputStream
FileOutputStream file = new FileOutputStream(String path);

// Creates an OutputStreamWriter
OutputStreamWriter output = new OutputStreamWriter(file);

– In the above example, we have created an OutputStreamWriter


named output along with the FileOutputStream named file.
– We can specify the type of character encoding (UTF8 or UTF16) to be
used to write data.
// Creates an OutputStreamWriter specifying the character encoding
OutputStreamWriter output = new OutputStreamWriter(file, Charset cs);

– Here, we have used the Charset class to specify the type of


character encoding.
OutputStreamWriter Class …
▪ Methods of OutputStreamWriter
– The OutputStreamWriter class provides implementations for
different methods present in the Writer class.
➢ write() Method:
− write() - writes a single character to the writer.
− write(char[] array) - writes the characters from the
specified array to the writer.
− write(String data) - writes the specified string to the
writer.
− …
OutputStreamWriter Class …
• Example: OutputStreamWriter to write data to a File
import [Link];
import [Link];

public class Main {


public static void main(String args[]) {
String data = "This is a line of text inside the file.";
try {
// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream("[Link]");
// Creates an OutputStreamWriter
OutputStreamWriter output = new OutputStreamWriter(file);
[Link](data); // Writes string to the file
[Link](); // Closes the writer
}
catch (Exception e) {}
}
}

• To write data to the file, we have used the write() method. Here,
when we run the program, the [Link] file is filled with the
following content.
This is a line of text inside the file.
OutputStreamWriter Class …
➢ getEncoding() Method:
− The getEncoding() method can be used to get the type of
encoding that is used to write data to the output stream. For
example,
import [Link];
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
try {
// Creates an output stream
FileOutputStream file = new FileOutputStream("[Link]");
// Creates an output stream reader with default encoding
OutputStreamWriter output1 = new OutputStreamWriter(file);
// Creates an output stream reader specifying the encoding
OutputStreamWriter output2 = new OutputStreamWriter(file, [Link]("UTF16"));
// Returns the character encoding of the output stream
[Link]("Character encoding of output1: " + [Link]());
[Link]("Character encoding of output2: " + [Link]());
// Closes the reader
[Link]();
[Link]();
}
catch(Exception e) {} Output:
}
}
The character encoding of output1: UTF8
The character encoding of output2: UTF-16
OutputStreamWriter Class …
➢ close() Method:
− To close the output stream writer, we can use the close()
method.
− Once the close() method is called, we cannot use the writer to
write the data.
➢ Other methods of OutputStreamWriter
Method Description
flush() forces to write all the data present in the writer
to the corresponding destination.
append() inserts the specified character to the current
writer.

FileWriter Class
• The FileWriter class of the [Link] package can be
used to write data (in characters) to files.
• It extends the OutputStreamWriter class.

• Create a FileWriter:
– In order to create a file writer, we must import the
[Link] package first. Once we import the package,
here is how we can create the file writer.
1. Using the name of the file
FileWriter output = new FileWriter(String name);

− Here, we have created a file writer that will be linked to the file specified by
the name.
FileWriter Class …
2. Using an object of the file
FileWriter output = new FileWriter(File fileObj);

− Here, we have created a file writer that will be linked to the file
specified by the object of the file.
• In the above example, the data is stored using some
default character encoding.
• However, since Java 11 we can specify the type of
character encoding (UTF8 or UTF16) as well.
FileWriter output = new FileWriter(String file, Charset cs);

• Here, we have used the Charset class to specify the


character encoding of the file writer.
FileWriter Class …
▪ Methods of FileWriter
– The FileWriter class provides implementations for different
methods present in the Writer class.
➢ write() Method:
– write() - writes a single character to the writer.
– write(char[] array) - writes the characters from the
specified array to the writer.
– write(String data) - writes the specified string to the
writer.
– …
FileWriter Class …
• Example: FileWriter to write data to a File
import [Link];

public class Main {


public static void main(String args[]) {
String data = "This is the data in the output file";
try {
// Creates a FileWriter
FileWriter output = new FileWriter("[Link]");
// Writes the string to the file
[Link](data);
// Closes the writer
[Link]();
}
catch (Exception e) {}
}
}

• To write data to the file, we have used the write() method.


• Here when we run the program, the [Link] file is filled with the
following content.
This is a line of text inside the file.
FileWriter Class …
➢ getEncoding() Method:
– The getEncoding() method can be used to get the type of
encoding that is used to write data. For example,
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
String filePath = "[Link]";
try {
// Creates a FileReader with default encoding
FileWriter output1 = new FileWriter(filePath);
// Creates a FileReader specifying the encoding
FileWriter output2 = new FileWriter(filePath, [Link]("UTF16"));
// Returns the character encoding of the reader
[Link]("Character encoding of output1: " + [Link]());
[Link]("Character encoding of output2: " + [Link]());
// Closes the reader
[Link]();
[Link]();
}
catch(Exception e) {} Output:
}
The character encoding of output1: UTF8
}
The character encoding of output2: UTF-16
FileWriter Class …
➢ close() Method:
– To close the file writer, we can use the close() method.
– Once the close() method is called, we cannot use the writer to
write the data.
➢ Other methods of FileWriter
Method Description
flush() forces to write all the data present in the
writer to the corresponding destination.
append() inserts the specified character to the current
writer.

PrintStream Class
PrintStream Class
• The PrintStream class of the [Link] package can be
used to print data to an output destination such as the
console, a file, or another output stream.
• It extends the abstract class OutputStream.

• Here is how it works:


− The PrintStream class extends OutputStream and is
designed to simplify the process of writing data to output
destinations like files or the console.
− If an I/O error occurs, the PrintStream does not throw an
exception. Instead, it records errors internally and you can check
them using checkError().
✓ To check if an error has occurred, you can use the checkError()
method, which returns a boolean value (true if an error occurred,
and false otherwise).
PrintStream Class …
• Example:
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
try {
PrintStream ps = new PrintStream("[Link]");
[Link]("Hello world!");

[Link]();
[Link]("This won't be written.");

// Check for errors


if ([Link]()) [Link]("An error occurred during printing.");
} catch (FileNotFoundException e) {[Link]([Link]);}
}
}
Output:
An error occurred during printing.

▪ After closing the PrintStream, an attempt is made to print more data, which
won’t succeed because the stream is closed.
▪ The checkError() method is then used to check whether an error occurred after
the closure.
PrintStream Class …
• N.B: The PrintStream class also has a feature of auto
flushing. This means it forces the output stream to write
all the data to the destination under one of the following
conditions:
✓ if newline character \n is written in the print stream.
✓ if the println() method is invoked.
✓ if an array of bytes is written in the print stream.
• Example:
// Writing a newline, may trigger flush automatically
[Link]("world!");

// Writing an array of bytes, which may trigger flush


byte[] arr = {65, 66, 67}; // corresponding to 'ABC'
[Link](arr);

// Explicit flush (if needed)


[Link]();
PrintStream Class …
• Create a PrintStream:
− In order to create a PrintStream, we must import the
[Link] package first. Once we import the package
here is how we can create the print stream.
▪ Using a File
// Creates a PrintStream
PrintStream output = new PrintStream(file, autoFlush); //autoFlush = true - the
//stream flushes automatically

• Here,
− we have created a print stream that will write formatted data to
the file represented by PrintStream.
− the autoFlush is an optional boolean parameter that specifies
whether to perform auto flushing or not.
− Example:
PrintStream ps = new PrintStream("[Link]");
[Link]("Hello World!");
Methods of PrintStream
• The PrintStream class provides various methods that
allow us to print data to the output.
➢ print() Method:
− print() - prints the specified data to the output stream.
− println() - prints the data to the output stream along with a
new line character at the end.
− Example 1: print() method with System class
public class Main {
public static void main(String[] args) {
String data = "Hello World.";
[Link](data);
}
}

• In Java, [Link] is a commonly used method to output text to the


console.
• The [Link] is an instance of the PrintStream class, which provides
methods for writing data to various output destinations, including the
console. Hence, we can use it to call all the methods of PrintStream class.
Methods of PrintStream …
• Example: print() method with PrintStream class
import [Link];

public class Main {


public static void main(String[] args) {
String data = "This is a text inside the file.";
try {
PrintStream output = new PrintStream("[Link]");
[Link](data);
[Link]();
}
catch(Exception e) {}
}
}
− To print data to the file, we have used the print() method.
Methods of PrintStream …
• printf() Method:
− The printf() method can be used to print the formatted
string. It includes 2 parameters: formatted string and arguments.
− For example,
printf("I am %d years old", 25);
▪ Here,
✓I am %d years old is a formatted string.
✓%d is integer data in the formatted string.
✓25 is an argument.
▪ The formatted string includes both text and data. And, the
arguments replace the data inside the formatted string. Hence,
the %d is replaced by 25.
Methods of PrintStream …
• Example: printf() method using PrintStream
class
import [Link];

public class Main {


public static void main(String[] args) {
try {
PrintStream output = new PrintStream("[Link]");
int age = 25;
[Link]("I am %d years old.", age);
[Link]();
}
catch(Exception e) {}
}
}

▪ In the above example, we have created a print stream named output.


The print stream is linked with the file [Link].
▪ To print the formatted text to the file, we have used the printf()
method.
Methods of PrintStream …
➢ Other Methods of PrintStream:
Methods Descriptions
close() closes the print stream.
checkError() checks if there is an error in the stream and
returns a boolean result.
append() appends the specified data to the stream.

File Handling in Java
File Handling
• It is the process of creating, reading, writing, and
manipulating files.
• Java provides several classes and methods within the
[Link] and [Link] packages to handle file operations
effectively.
• Basic Classes for File Handling:
– File: Represents the file or directory in the system. It is used to
create new files, delete files, and get file information.
– FileReader and FileWriter: Used for reading and writing
text files character by character.
– BufferedReader and BufferedWriter: Used for efficient
reading and writing of text files by buffering characters.
– FileInputStream and FileOutputStream: Used for
reading and writing binary data from files.
– Scanner: Often used for reading input from files.
File Class
• The File class is the foundation for file and directory
handling in Java. It provides methods to create, delete,
and check properties of files and directories.
• File and Directory:
– A file is a named location that can be used to store related
information.
– A directory is a collection of files and subdirectories. A directory
inside a directory is known as subdirectory.
• Create a Java File Object:
– To create an object of File, we need to import the [Link]
package first. Once we import the package, here is how we can
create objects of file.
// creates an object of File using the path
File file = new File(String pathName);
▪ Here, we have created a file object named file. The object can be used to work
with files and directories.
File Operation Methods
Operation Method Package
To create file createNewFile() [Link]
To delete file delete() [Link]
To check if the file exists exists() [Link]

To return the name of getName() [Link]


the file
To return the absolute getAbsolutePath() [Link]
file path
To return the size of the length() [Link]
file in bytes
To check if it is a isDirectory() [Link]
directory
To read file read() [Link]
To write file write() [Link]
File Operations
• You can perform various file operations in Java to manage
files and directories on your computer.
• Let us understand these operations with the respective
file handling programs in Java.
– Creating a file
– Checking if a file exists
– Renaming a file
– Writing to a file
– Reading from a file
– Copying a file
– Moving a file
– Creating a directory
– Listing files in a directory
– Deleting a file
– Getting information of a file
Creating a file
• In Java, we can create a file using the
createNewFile() method of the File class. This
method returns true if the file is created, otherwise, false
is returned if the file already exists.
import [Link].*;

class Main {
public static void main(String[] args) throws IOException {
// an object of file class
File f = new File("[Link]");

// creating a new file


Boolean result = [Link]();

if(result == true) [Link](f+" created successfully.");


else [Link]("File cannot be created due to some error.");
}
}
Checking if a file exists
• You can check if a file exists on your system using the
File class and its exists() method.
import [Link].*;

class Main {
public static void main(String[] args) {
File f = new File("[Link]");

if([Link]() == true)
[Link]("File exists!");
else
[Link]("File does not exist.");
}
}
Renaming a file
• You can rename a file using the File class and its
renameTo() method, which allows you to change the
name of the file.
import [Link].*;

class Main {
public static void main(String[] args) {
File oldFile = new File("[Link]");
File newFile = new File("[Link]");

if([Link](newFile) == true)
[Link]("File renamed successfully!");
else
[Link]("File renaming failed.");
}
}
Writing to a file
• The write operation on a file means storing the data in a
file.
• To perform write operations on a file, we will use the
write() method along with the FileWriter class.
We should use the close() method to close the stream
to retrieve the allocated resources.
import [Link].*;

class Main {
public static void main(String[] args) throws IOException {
// creating a new file and writing data to a file
FileWriter fw = new FileWriter("[Link]");
String s = "Welcome, this is File Handling in Java.";
[Link](s);

// closing a file
[Link]();
}
}
Reading a file
• The read operation means accessing or retrieving the data
stored from a file.
• To perform a read operation on a file, we will use the
Scanner class along with the hasNextLine() and
nextLine() methods to retrieve data from a file. We
should use the close() method to close the stream.
import [Link].*;
import [Link];
class Main {
public static void main(String[] args) throws IOException {
File f = new File("[Link]");
Scanner sc = new Scanner(f);
while([Link]() == true)
{
String str = [Link]();
[Link](str);
}
[Link](); // closing a file
}
}
Moving a file
• Moving a file involves both copying it to a new location
and deleting the original file. This can be achieved using
the renameTo() method.
import [Link].*;

class Main {
public static void main(String[] args) {
File sourceFile = new File("[Link]");
File destinationFile = new File("targetDirectory/[Link]");

if([Link](destinationFile) == true)
[Link]("File moved successfully!");
else
[Link]("File moving failed.");
}
}
Creating a directory
• To create a new directory (folder) in your file system, you
can use the mkdir()method of the File class.
import [Link].*;

class Main {
public static void main(String[] args) {
File directory = new File("newDirectory");

if([Link]() == true)
[Link]("Directory created successfully!");
else
[Link]("Directory creation failed.");
}
}
Listing files in a directory
• You can list all the files and subdirectories present in a
directory using the list() or listFiles() method
of the File class.
import [Link].*;

class Main {
public static void main(String[] args) {
File directory = new File("myFolder");
File[] files = [Link]();

if(files != null) {
for(File f : files)
[Link]([Link]());
}
}
}
Deleting a file
• In file handling, we can delete a file using the delete()
method of the File class.
• There is no need to close the file using close() because
neither the FileWriter nor the Scanner classes are
used to delete a file.
import [Link].*;

class Main {
public static void main(String[] args) throws IOException {
File f = new File("[Link]");
Boolean result = [Link]();

if(result == true) [Link](f + " deleted successfully.");


else [Link]("File cannot be deleted due to some error.");
}
}
Getting file information
• There are few methods in Java that I have discussed
earlier at methods of file class to get the information of
the file.
import [Link].*;

class Main {
public static void main(String[] args) throws IOException {
File f = new File("[Link]");

[Link]();

String filename = [Link]();

[Link]("File Name is " + filename);


[Link]("Absolute path of " + filename + ": " + [Link]());
[Link]("length of " + filename + ": " + [Link]());
[Link](“\nIs " + filename + " readable? " + [Link]());
[Link]("Is " + filename + " writable? " + [Link]());
[Link]("Is " + filename + " exists? " + [Link]());
}
}
Error Handling in File Operations
• File operations can fail due to reasons like file not found,
permission issues, or insufficient storage.
• Java uses exceptions to handle such cases.
• Example:
import [Link];
import [Link];
import [Link];

class Main {
public static void main(String[] args) {
try {
File file = new File("nonexistent_directory/[Link]");
FileWriter writer = new FileWriter(file);
[Link]("Error Handling!");
[Link]();
} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
}
}
}
Output:
An error occurred: nonexistent_directory\[Link] (The system cannot find the path
specified)
Modern File Handling: NIO (New I/O)
• The [Link] package introduced in Java 7 provides
advanced features for file handling, such as:
– Paths: Represents file paths.
– Files: Provides static methods for file operations (e.g., copy(),
move(), delete()).
– Example 1: Copying a file using [Link]()
import [Link].*;
import [Link];
class Main {
public static void main(String[] args) {
try {
Path source = [Link]("[Link]");
Path target = [Link]("[Link]");
[Link](source, target, StandardCopyOption.REPLACE_EXISTING);
[Link]("File copied successfully!");
} catch (IOException e) {
[Link]();
}
}
}
Output:
File copied successfully!
Modern File Handling: NIO (New I/O) …
– Example 2: Moving a file using [Link]()
import [Link].*;
import [Link];

class Main {
public static void main(String[] args) {
Path source = [Link]("[Link]");
Path target = [Link]("targetDirectory/[Link]");

try {
[Link](source, target, StandardCopyOption.REPLACE_EXISTING);
[Link]("File moved successfully!");
} catch (IOException e) {
[Link]();
}
}
}
Output:
File moved successfully!
Modern File Handling: NIO (New I/O) …
– Example 3: Deleting a file using [Link]()
import [Link].*;
import [Link];

class ByteStreamExample {
public static void main(String[] args) {
Path path = [Link]("[Link]");

try {
[Link](path); // Deletes the file if it exists
[Link]("File deleted successfully.");
} catch (IOException e) {
[Link]("Failed to delete the file: " + [Link]());
}
}
}
Output:
File deleted successfully!

• Note: Prefer NIO for large file handling, and more


advanced operations.
Thank You!

You might also like