0% found this document useful (0 votes)
17 views7 pages

Java File Handling and Stream Concepts

Java Chapter - 5

Uploaded by

rasadagency
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)
17 views7 pages

Java File Handling and Stream Concepts

Java Chapter - 5

Uploaded by

rasadagency
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

1

UNIT-V

Files: Introduction
In Java, with the help of File Class, we can work with files. This File Class is inside the [Link]
package. The File class can be used by creating an object of the class and then specifying the
name of the file.
Why File Handling is Required?
• File Handling is an integral part of any programming language as file handling enables us
to store the output of any particular program in a file and allows us to perform certain
operations on it.
• In simple words, file handling means reading and writing data to a file.

// Importing File Class


import [Link];

class GFG {
public static void main(String[] args)
{

// File name specified


File obj = new File("[Link]");
[Link]("File Created!");
}
}
Output
File Created!

In Java, the concept Stream is used in order to perform I/O operations on a file. So at first, let us
get acquainted with a concept known as Stream in Java.

Concept of streams
• A stream (torrent/river) is a sequence of data. In Java, a stream is composed of bytes.
• It is called a stream because it is like a stream of water that continues to flow. In general,
a stream means continuous flow of data.
• This concept is used to perform I/O operations on a file.
• Java I/O (Input and Output) is used to process the input and produce the output.
• Java uses the concept of a stream to make I/O operation fast. The [Link] package
contains all the classes required for input and output operations.
• We can perform file handling in Java by Java I/O API.
• In Java, three streams are created for us automatically. All these streams are attached
with the console.
[Link] : standard output stream
[Link] : standard input stream
2

[Link] : standard error stream

There are two types of streams:


1. Input Stream:
The Java InputStream class is the superclass of all input streams. The input stream is used to read
data from numerous input devices like the keyboard, network, etc. InputStream is an abstract
class, and because of this, it is not useful by itself. However, its subclasses are used to read data.
Creating an InputStream
// Creating an InputStream
InputStream obj = new FileInputStream();

2. Output Stream:
The output stream is used to write data to numerous output devices like the monitor, file, etc.
OutputStream is an abstract superclass that represents an output stream. OutputStream is an
abstract class and because of this, it is not useful by itself. However, its subclasses are used to
write data.
Creating an OutputStream
// Creating an OutputStream
OutputStream obj = new FileOutputStream();

Stream Classes
Byte Stream
InputStream
OutputStream
Character Stream

Byte stream classes


- Byte Streams are used to read or write a single byte (8-bits) data with files.
- Here you work with raw bytes, which could be characters, image data, Unicode data
(which takes 2 bytes to represent a character), etc.
- All byte stream classes are derived from base abstract classes
called InputStream and OutputStream.

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.

Create an InputStream
In order to create an InputStream, we must import the [Link] package first.
// Creates an InputStream
3

InputStream object1 = 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.

Reading Data from a File using FileInputStream


- FileInputStream class in Java is useful to read data from a file in the form of a sequence
of bytes.
- FileInputStream is meant for reading streams of raw bytes such as image data. For
reading streams of characters, consider using FileReader.
- The read() method of InputStream class reads a byte of data from the input stream. The
next byte of data is returned, or -1 if the end of the file is reached and throws an exception
if an I/O error occurs.

File Name: “[Link]”


// Java program to demonstrate the working of the FileInputStream read() method
import [Link];

public class abc


{
public static void main(String args[])
{
try
{
FileInputStream input = new FileInputStream("[Link]");
[Link]("Data in the file: ");

//Reads the first byte


int i = [Link]();
while(i != -1)
{
[Link]((char)i); //see the below note

// Reads next byte from the file


i = [Link]();
}
[Link]();
}

catch(Exception e) //catch (exception(type) e(object)


{
[Link]();
}
}
4

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.

Create an OutputStream
In order to create an OutputStream, we must import the [Link] package
first.
// Creates an OutputStream
OutputStream object = 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.

Creating a File using FileOutputStream


- FileOutputStream class belongs to byte stream and stores data in the form of individual
bytes. It can be used to create text files. A file represents storage of data on a second
storage media like a hard disk or CD.
- FileOutputStream is meant for writing streams of raw bytes such as image data. For
writing streams of characters, consider using FileWriter.
- Whether or not a file is available or may be created depends upon the underlying
platform. Some platforms, in particular, allow a file to be opened for writing by only one
FileOutputStream (or other file-writing objects) at a time. In such situations, the
constructors in this class will fail if the file involved is already open.

To write the contents of a file using this class −


• First of all, you need to instantiate this class by passing a string variable or a File Object,
representing the path of the file to be read.
o Instantiate FileOutputStream class by passing a string variable (file_path).
FileOutputStream outputStream = new FileOutputStream("file_path");
OR,
o Instantiate FileoutputStream class by passing a File Object
File file = new File("file_path");
FileOutputStream outputStream = new FileOutputStream(file);

Example:
import [Link];

class FileOutputStreamExample
{
5

public static void main(String args[])


{
try
{
FileOutputStream fout = new FileOutputStream("E:\\[Link]");
[Link](65);
[Link]();
[Link]("success...");
}
catch(Exception e)
{
[Link]("File not Found " + e);
}
}
}
Output:
A (it will write character A in ‘[Link]’ in E: drive, because ASCII 65 is A)

Character stream classes


- The [Link] package provides CharacterStream classes to overcome the limitations of
ByteStream classes, which can only handle the 8-bit bytes and is not compatible to work
directly with the Unicode characters. CharacterStream classes are used to work with 16-
bit Unicode characters. They can perform operations on characters, char arrays and
Strings.
- However, the CharacterStream classes are mainly used to read characters from the source
and write them to the destination. For this purpose, the CharacterStream classes are
divided into two types of classes, I.e., Reader class and Writer class.

Reader Class
- Reader class is used to read the 16-bit characters from the input stream.
- However, it is an abstract class and can't be instantiated, but there are various
subclasses that inherit the Reader class and override the methods of the Reader class.
- All methods of the Reader class throw an IOException.
- Some subclasses of the Reader class are given below:
o BufferedReader
o FileReader
o InputStreamReader

Writer Class
- Writer class is used to write 16-bit Unicode characters to the output stream.
- The methods of the Writer class generate IOException.
6

- Like Reader class, Writer class is also an abstract class that cannot be instantiated;
therefore, the subclasses of the Writer class are used to write the characters onto the
output stream.
- Some subclasses of the Writer class are given below:
o BufferedWriter
o FileWriter
o InputStreamWriter

Reading and writing files

Reading from a file


- The FileReader class of the [Link] package can be used to read data (in characters) from
files.
- It extends the InputSreamReader class.

To read data from a file, you need to follow the following steps:
1. Create a File object that represents the file you want to read.
2. Create a FileReader object that reads data from the file.
3. Use the read() method of the FileReader object to read data from the file.
4. Close the FileReader object using the close() method.

Example:
import [Link];
import [Link];
import [Link];

public class ReadFromFile {


public static void main(String[] args) throws IOException {
File file = new File("[Link]");
FileReader fr = new FileReader(file); // FileReader is subclass of Reader abstract class
int ch;
while ((ch=[Link]()) != -1) {
[Link]((char)ch);
}
[Link]();
}
}

Writing to a File
- The FileWriter class of the [Link] package can be used to write data (in characters) to
files.
- Unlike(not like) FileOutputStream class, you don't need to convert string into
byte array because it provides method to write string directly.
7

To write data to a file, you need to follow the following steps:


1. Create a File object that represents the file you want to write to.
2. Create a FileWriter object that writes data to the file.
3. Use the write() method of the FileWriter object to write data to the file.
4. Close the FileWriter object using the close() method.
Example:
import [Link];
import [Link];
import [Link];

public class WriteToFile {


public static void main(String[] args) throws IOException {
File file = new File("[Link]");
FileWriter fw = new FileWriter(file); // FileReader is subclass of Reader abstract class

[Link]("Hello World!");
[Link]();
}
}

You might also like