0% found this document useful (0 votes)
12 views21 pages

Java I/O: Managing Streams and Files

Notes

Uploaded by

Om Dighule
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)
12 views21 pages

Java I/O: Managing Streams and Files

Notes

Uploaded by

Om Dighule
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

Chapter 6.

Managing Input/Output/Files in Java


6.1 Introduction and concept of streams.
6.2 Stream Classes
6.3 Byte Stream Classes: Input Stream Classes, Output Stream Classes.
6.4 Character Stream Classes, Using streams.
6.5 Using File Class: I/O Exceptions, Creation of Files, Reading/Writing characters,
Reading/Writing Bytes, Handling Primitive Data types.

6.1 Introduction and concept of streams.

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.

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1) [Link]: standard output stream-This is the standard output stream that is used to
produce the result of a program on an output device like the computer screen.

This stream uses all 3 functions to output the data:


• print()
• println()
• printf()

2) [Link]: standard input stream-This is the standard input stream that is used to read
characters from the keyboard or any other standard input device.
3) [Link]: standard error stream- This is the standard error stream that is used to output
all the error data that a program might throw, on a computer screen or any standard output
device.
Let's see the code to print output and an error message to the console.
[Link]("simple message");
[Link]("error message");
Let's see the code to get input from console.
int i=[Link]();//returns ASCII code of 1st character
[Link]((char)i);//will print the character

6.2 Stream Classes


A stream is a communication channel that a program has with the outside world. It is used to
transfer data items in succession.
An Input/Output (I/O) Stream represents an input source or an output destination. A stream
can represent many different kinds of sources and destinations, including disk files, devices,
other programs, and memory arrays.
Streams support many different kinds of data, including simple bytes, primitive data types,
localized characters, and objects. Some streams simply pass on data; others manipulate and
transform the data in useful ways.
No matter how they work internally, all streams present the same simple model to programs
that use them: A stream is a sequence of data.
Reading information into a program.
A program uses an input stream to read data from a source, one item at a time:
Writing information from a program.
A program uses an output stream to write data to a destination, one item at time:

The data source and data destination pictured above can be anything that holds, generates, or
consumes data. Obviously this includes disk files, but a source or destination can also another
program, a peripheral device, a network socket, or an array.
Classification of Streams

In general, a Stream will be an input stream or, an output stream.


• InputStream − This is used to read data from a source.
• OutputStream − This is used to write data to a destination.
Based on the data they handle there are two types of streams −
• Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes
read/write data of 8 bits. Using these you can store characters, videos, audios, images
etc.
• Character Streams − These handle data in 16 bit Unicode. Using these you can read and
write text data only.

6.3 Byte Stream Classes: Input Stream Classes, Output Stream Classes.

• Byte streams can be used to read or write bytes serially from an external device. All the
byte streams are derived from the abstract superclass InputStream and OutputStream.
• This is used to process data byte by byte (8 bits). Though it has many classes, the
FileInputStream and the FileOutputStream are the most popular ones. The
FileInputStream is used to read from the source and FileOutputStream is used to write
to the destination.

6.3.1 InputStream:

Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
[Link] is an abstract class that contains the basic methods for reading
raw bytes of data from a stream. Let's understand the working of Java OutputStream
and InputStream by the figure given below.
InputStream Hierarchy

Methods Of InputStream Class:

Method Description
This method returns an estimate of the number of bytes that can be
int available() read (or skipped over) from this input stream without blocking by
the next invocation of a method for this input stream.
This method closes this input stream and releases any system
void close()
resources associated with the stream.
void mark(int readlimit) This method marks the current position in this input stream.
This method tests if this input stream supports the mark and reset
boolean markSupported()
methods.
abstract int read() This method reads the next byte of data from the input stream.
This method reads some number of bytes from the input stream and
int read(byte[] b)
stores them into the buffer array b.
This method reads up to len bytes of data from the input stream into
int read(byte[] b, int off, int len)
an array of bytes.
This method repositions this stream to the position at the time the
void reset()
mark method was last called on this input stream.
This method skips over and discards n bytes of data from this input
long skip(long n)
stream.

6.3.2 OutputStream:
Java application uses an output stream to write data to a destination. It may be a file, an
array, peripheral device or socket.
OutputStream Hierarchy

Methods of OutputStream Class:

Method Description
1) public void write(int)throws
is used to write a byte to the current output stream.
IOException
2) public void write(byte[])throws is used to write an array of byte to the current
IOException output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.

6.3.3 FileInputStream
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc.
Java FileInputStream class methods
Method Description
It is used to return the estimated number of bytes that can be read
int available()
from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to [Link] bytes of data from the input stream.
int read(byte[] b, int off,
It is used to read up to len bytes of data from the input stream.
int len)
It is used to skip over and discards x bytes of data from the input
long skip(long x)
stream.
FileChannel It is used to return the unique FileChannel object associated with the
getChannel() file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
It is used to ensure that the close method is call when there is no
protected void finalize()
more reference to the file input stream.
void close() It is used to closes the stream.

Program for FileInputStream:


import [Link].*;
class simpleread
{
public static void main(String args[])
{
try{
FileInputStream fin=new FileInputStream("[Link]");
int i;
while((i=[Link]())!=-1)
[Link]((char)i);
[Link]();
}catch(Exception e)
{
[Link](e);
}
}
}
First we have to create [Link] file as given below:
OUTPUT:
Run java program in command prompt. It will read the data from [Link] document.

6.3.4 FileOutputStream

• Java FileOutputStream is an output stream used for writing data to a file.


• If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream class.
But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
• It is used to create a file and write data into it. The stream would create a file, if it
doesn’t already exist, before opening it for output.
• Constructors are:
1. FileOutputStream(String filepath)
2. FileOutputStream(File fileObj)
3. FileoutputStream(String filePath, boolean append)
4. FileOutputStream(File fileObj, boolean append)
FileOutputStream class methods
Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
It is used to write [Link] bytes from the byte array to the file
void write(byte[] ary)
output stream.
void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at offset
int len) off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
It is used to return the file channel object associated with the file
FileChannel getChannel()
output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
void close() It is used to closes the file output stream.

• Program for FileOutputStream


import [Link].*;
class simplewrite
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("[Link]");
String s="Java is my favorite language";
byte b[]=[Link]();
[Link](b);
[Link]();
[Link]("Success...");
}catch(Exception e)
{
[Link](e);
}
}
}
OUTPUT:

It will create [Link] document and writes data into it.

6.4 Character Stream Classes


• In Java, characters are stored using Unicode conventions. Character stream
automatically allows us to read/write data character by character.
• Though it has many classes, the FileReader and the FileWriter are the most popular
ones. FileReader and FileWriter are character streams used to read from the source and
write to the destination respectively.
• Character streams are implemented by Reader and Writer classes and their subclasses.

Classification of Character Stream


6.4.1 Reader
The [Link] class is abstract class for reading character streams. The classes and
methods are functionally very similar to the input stream classes. Reader stream classes are
designed to read character from the files. Reader class is the base class for all other classes in
its group.
Class constructors

1. protected Reader()
2. protected Reader(Object lock)

The foll. Figure shows classes of Reader:

Methods of Reader
Modifier and
Method Description
Type
It closes the stream and releases any system resources
abstract void close()
associated with it.
int read() It reads a single character.
read(char[]
int It reads characters into an array.
cbuf)
boolean ready() It tells whether this stream is ready to be read.
void reset() It resets the stream.
long skip(long n) It skips characters.

6.4.2 Writer
It is an abstract class for writing to character streams. The methods that a subclass must
implement are write(char[], int, int), flush(), and close().
Constructor

Modifier Constructor Description


It creates a new character-stream writer whose critical sections
protected Writer()
will synchronize on the writer itself.
Writer(Object It creates a new character-stream writer whose critical sections
protected
lock) will synchronize on the given object.
The foll. Figure shows classes of Writer.

Methods of Writer
6.4.3 FileReader
• FileReader class is used to read data from the file. It translates bytes from a file into
a character stream.
• Constructors are:
(1) FileReader(String path)
(2) FileReader(File obj)
• Program for FileReader class
import [Link];
import [Link];
class fileread
{
public static void main(String args[])throws Exception
{
File f=new File("[Link]");
if ([Link]())
{
FileReader fr=new FileReader(f);
int ch;
while((ch= [Link]())!=-1)
[Link]((char) ch);
[Link]();
}
}
}
[Link] document
OUTPUT:

6.4.4 FileWriter
• FileWriter class is used to write character into the file.
• Constructors are
(1) FileWriter(String path)
(2) FileWriter(String path, boolean append)
(3) FileWriter(File obj)
(4) FileWriter(File obj, boolean append)
• Program for FileWriter
import [Link];
class filewrite
{
public static void main(String args[])throws Exception
{
String str="I would like to learn advanced java programming also";
char buf[] = [Link]();
int len=[Link];
FileWriter f=new FileWriter("[Link]");
[Link](buf);
[Link]();
FileWriter f1=new FileWriter("[Link]");
[Link](buf, [Link]/4, [Link]/4);
[Link]();
}
}
OUTPUT:

After compilation and running program it will execute 2 documents namely, [Link]
and [Link].
6.5 Using File Class:
• [Link] package includes a class known as File class.
• The [Link] is the central class that works with files and directories. The instance
of this class represents the name of a file or directory on host file system.
• Java File class represents the files and directory pathnames in an abstract manner.
This class is used for creation of files and directories., file searching, file deletion etc.
• Constructors:
(1) File(String path): Creates File object for default directory.
(2) File(String dirpath, String fname): Creates File object for directory path given as
string.
(3) File(File dir, String fname): Creates File object for directory.
Methods of File class
[Link]. Method & Description
public String getName()
1
Returns the name of the file or directory denoted by this abstract pathname.
public String getParent()
2 Returns the pathname string of this abstract pathname's parent, or null if this
pathname does not name a parent directory.
public String getPath()
3
Converts this abstract pathname into a pathname string.
public boolean isAbsolute()
4 Tests whether this abstract pathname is absolute. Returns true if this abstract
pathname is absolute, false otherwise.
public boolean canRead()
Tests whether the application can read the file denoted by this abstract pathname.
5
Returns true if and only if the file specified by this abstract pathname exists and can be
read by the application; false otherwise.
public boolean canWrite()
Tests whether the application can modify to the file denoted by this abstract
6 pathname. Returns true if and only if the file system actually contains a file denoted by
this abstract pathname and the application is allowed to write to the file; false
otherwise.
public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory. Returns true if
7
and only if the file denoted by this abstract pathname exists and is a directory; false
otherwise.
public boolean isFile()
8 Tests whether the file denoted by this abstract pathname is a normal file. A file is
normal if it is not a directory and, in addition, satisfies other system-dependent criteria.
Any non-directory file created by a Java application is guaranteed to be a normal file.
Returns true if and only if the file denoted by this abstract pathname exists and is a
normal file; false otherwise.
public long lastModified()
Returns the time that the file denoted by this abstract pathname was last modified.
9 Returns a long value representing the time the file was last modified, measured in
milliseconds since the epoch ([Link] GMT, January 1, 1970), or 0L if the file does not
exist or if an I/O error occurs.
public long length()
10 Returns the length of the file denoted by this abstract pathname. The return value is
unspecified if this pathname denotes a directory.
public boolean createNewFile() throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a
11
file with this name does not yet exist. Returns true if the named file does not exist and
was successfully created; false if the named file already exists.
public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname
12
denotes a directory, then the directory must be empty in order to be deleted. Returns
true if and only if the file or directory is successfully deleted; false otherwise.
public boolean mkdir()
13 Creates the directory named by this abstract pathname. Returns true if and only if the
directory was created; false otherwise.
public boolean mkdirs()
Creates the directory named by this abstract pathname, including any necessary but
14
nonexistent parent directories. Returns true if and only if the directory was created,
along with all necessary parent directories; false otherwise.
public String toString()
15 Returns the pathname string of this abstract pathname. This is just the string returned
by the getPath() method.
Program for File class:
import [Link];
class file
{
public static void main(String[] args)
{
File f=new File("C:/Users/Shashikant/Desktop/fileio/[Link]");
[Link]("is File="+[Link]());
[Link]("Name="+[Link]());
[Link]("Size="+[Link]());
[Link]("Path="+[Link]());
[Link]("Parent="+[Link]());
[Link]("Hidden="+[Link]());
}
}

Output:
We are getting the output from [Link] file.

6.5.1 I/O Exceptions:


IOException is a checked exception. A checked exception is handled in the java code by the
developer. This exception object has a string message which is the root cause for the failure.
Subclasses of I/O Exceptions are given as below:
• FileNotFoundException: Thrown when the attempt to access the file specified by a
given pathname fails since the file does not exist.
• EOFException: Thrown when end of file is detected while reading.
• CharConversionException: Thrown when a character conversion problem occurs in a
character stream operation that must convert local character codes to Unicode or vice
versa.
• UnSupportedEncodingException: Thrown when an unknown character encoding is
specified.
• ObjectStreamException: The superclass for all the Object stream related exceptions.

6.5.2 Handling Primitive Data Types


The basic input and output streams provide read/ write methods that can be used for reading/
writing bytes or characters.
To read/ write the primitive data types such as integers and doubles, we can use filter classes as
wrappers on the existing I / O streams to filter data to the original stream.
The two filter classes supported for creating “data streams” for primitive data types are:

• DataI nputStream
• DataOutputStream

(1) DataInputStream
➢ [Link] reads primitive data from file through input stream
which is machine independent.
➢ Program for DataInputStream (Read data from file, convert it to uppercase and
print.)
Code:
import [Link].*;
public class filetest
{
public static void main(String args[])throws IOException
{
String file="[Link]";
FileInputStream fin=new FileInputStream(file);
DataInputStream din=new DataInputStream(fin);
byte b[]=new byte[0];
[Link](b);
String str;
while((str=[Link]())!=null)
{
[Link](str);
String str1=[Link]();
[Link](str1);
}
[Link]();
[Link]();
}
}
[Link] document

Output:

(2) DataOutputStream
➢ [Link] helps to write primitive data type in a file as an Output
Stream. DataInputStream can then read it back.
➢ Program for DataOutputStream
import [Link].*;
public class filetest1
{
public static void main(String args[])throws IOException
{
String file="[Link]";
FileOutputStream fos=new FileOutputStream(file);
DataOutputStream dos=new DataOutputStream(fos);
int num=100;
[Link](num);
char ch='K';
[Link](ch);
double d=1.2;
[Link](d);
boolean b=true;
[Link](b);
[Link]();
[Link]();
[Link]("Data written in file");
FileInputStream fin=new FileInputStream(file);
DataInputStream dis=new DataInputStream(fin);
int num1=[Link]();
[Link]("Integer:"+num1);
char ch1=[Link]();
[Link]("Character:"+ch1);
double d1=[Link]();
[Link]("Double:"+d1);
boolean b1=[Link]();
[Link]("Boolean:"+b1);
[Link]();
}
}
OUTPUT:

You might also like