Chapter 06
Chapter 06
6th Unit
Mr. R. M. Patil
SY CO, JPR
2023-2024
1
Introduction & Concept of Streams – W-15
The java.io package contains nearly every class you
might ever need to perform input and output (I/O) in Java.
Stream
A stream can be defined as a sequence of data. There are
two kinds of Streams −
InputStream − The InputStream is used to read data from a
source.
OutputStream − The OutputStream is used for writing data
to a destination.
2
Introduction & Concept of Streams
Byte Streams:
Java byte streams are used to perform input and output of 8-bit
bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
Character Streams:
Java character streams are used to perform input and output of 16-
bit unicodes (Characters).
Though there are many classes related to byte streams but the most
frequently used classes are, FileReader and FileWriter.
5
Stream Classes – Byte Stream Classes
6
Byte Stream Classes – 1. InputStream Class
7
Byte Stream Classes – 1. InputStream Class
8
Byte Stream Classes – 1. InputStream Class
Methods of InputStream class.
These methods are inherited by InputStream subclasses.
Methods Description
This method returns the number of bytes
int available()
that can be read from the input stream.
This method reads the next byte out of the
abstract int read()
input stream.
This method reads a chunk of bytes from
int read(byte[] b) the input stream and store them in its byte
array, b.
This method closes this input stream and
close() also frees any resources connected with
this input stream.
9
Byte Stream Classes – 2. OutputStream Class
10
Byte Stream Classes – 2. OutputStream Class
11
Byte Stream Classes – 2. OutputStream Class
Methods of OutputStream class.
Methods of OutputStream class provide support for writing bytes to the output
stream. As this is an abstract class. Hence, some undefined abstract methods are
defined in the subclasses of OutputStream.
Methods Description
Class Description
13
Byte Stream Classes – ByteArrayInputStream Example
import java.io.*;
class demo
{
public static void main(String args[]) throws IOException
{
byte b[]="this is my first program".getBytes();
ByteArrayInputStream inp =new ByteArrayInputStream(b);
int n=inp.available();
System.out.println("Number of available bytes: "+n);
while((i=inp.read()) != -1)
{
System.out.print((char)i);
}
}
}
14
Byte Stream Classes – ByteArrayOutputStream Example
import java.io.*;
class demo
{
public static void main(String args[]) throws IOException
{
ByteArrayOutputStream out=new ByteArrayOutputStream();
byte b[]="Today is a bright sunny day".getBytes();
out.write(b);
System.out.println(out.toString() ); /*converting byte array to String*/
OR
16
Reading/Writing Bytes
Reading/Writing Bytes
1. FileInputStream
2. FileOutputStream
3. BufferedInputStream
&
BufferedOutputStream
17
Reading/Writing Bytes : 1. FileInputStream
18
Reading/Writing Bytes : 1. FileInputStream
Method Description
It is used to return the estimated number of
int available() bytes that can be read from the input
stream.
It is used to read the byte of data from the
int read()
input stream.
It is used to read up to b.length bytes of
int read(byte[] b)
data from the input stream.
It is used to skip over and discards x bytes
long skip(long x)
of data from the input stream.
void close() It is used to closes the stream.
19
import java.io.*;
public class DataStreamExample read single character
{ using
public static void main(String args[]) FileInputStream
{
try
{
FileInputStream f=new FileInputStream("D:\\testout.txt");
int i=f.read();
System.out.print((char)i);
f.close();
}
catch(Exception e)
{
System.out.println(e);
}
} 20
import java.io.*;
public class DataStreamExample
{
read all characters
public static void main(String args[]) using
{ FileInputStream
try
{
FileInputStream f=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=f.read())!=-1)
{
System.out.print((char)i);
}
f.close();
}
catch(Exception e)
{
System.out.println(e);
}
} 21
Reading/Writing Bytes : 2. FileOutputStream
java.io.FileOutputStream writes byte stream into a file system.
It has following constructors :
Method Description
It is used to write ary.length bytes from
void write(byte[] ary)
the byte array to the file output stream.
It is used to write the specified byte to
void write(int b)
the file output stream.
It is used to closes the file output
void close()
stream.
23
import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream f=new FileOutputStream("D:\\testout.txt");
f.write(65);
f.close();
System.out.println("success...");
}
catch(Exception e) Write byte using
{ FileOutputStream
System.out.println(e);
} 24
import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream f=new FileOutputStream("D:\\testout.txt");
String s="Welcome to java.";
byte b[]=s.getBytes(); //converting string into byte array
f.write(b);
f.close();
System.out.println("success...");
}
catch(Exception e)
{
System.out.println(e); Write a String
}
} using
} FileOutputStream
25
Reading/Writing Bytes :
3. BufferedIntputStream & BufferedOutputStream
Java BufferedInputStream class is used to read information from
stream.
It adds more efficiency than to write data directly into a stream. So,
it makes the performance fast.
26
import java.io.*;
public class Demo
{
read all characters
public static void main(String args[]) using
{ BufferedInputStream
try
{
FileInputStream f=new FileInputStream("D:\\testout.txt");
BufferedInputStream b=new BufferedInputStream(f);
int i;
while((i=b.read())!=-1)
{
System.out.print((char)i);
}
b.close(); f.close();
}
catch(Exception e)
{
System.out.println(e);
27
}}}
import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
30
Reading/Writing Characters
Reading/Writing Characters
1. FileReader &
FileWriter
2. charArrayReader &
charArrayWriter
3. BufferedReader &
BuferedWriter
31
Reading/Writing Characters : 1. FileReader & FileWriter
32
port java.io.FileReader; Example : FileReader
public class FileReaderExample
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("D:\\testout.txt");
int i=0;
while((i=fr.read())!=-1)
{
System.out.print((char)i);
}
fr.close();
}
}
33
import java.io.FileWriter;
public class FileWriterExample Example : FileWriter
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Success...");
}
} 34
Reading/Writing Characters : 2. charArrayReader & charArrayWriter
35
Example : charArrayReader
import java.io.CharArrayReader;
public class CharArrayExample
{
public static void main(String[] ag) throws Exception
{
char[] ary = { 'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't' };
CharArrayReader r = new CharArrayReader(ary);
int k = 0;
while ((k = r.read()) != -1) // Read until the end of a file
{
char ch = (char) k;
System.out.print(ch + " : ");
System.out.println(k);
}
}
} 36
import java.io.*; Example : charArrayWriter
public class CharArrayWriterExample
{
public static void main(String args[]) throws Exception
{
CharArrayWriter out=new CharArrayWriter();
out.write("Welcome to javaTpoint");
FileWriter f1 = new FileWriter("D:\\a.txt");
FileWriter f2 = new FileWriter("D:\\b.txt");
out.writeTo(f1);
out.writeTo(f2);
f1.close();
f2.close();
System.out.println("Success...");
}
} 37
Reading/Writing Characters : 3. BufferReader & BufferWriter
38
import java.io.*; Example : BufferReader
public class BufferedReaderExample
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);
String str=null;
while((str=br.readLine())!=null)
{
System.out.print(str);
}
br.close();
fr.close();
}
} 39
Example : BufferWriter
import java.io.*;
public class BufferedWriterExample
{
public static void main(String[] args) throws Exception
{
FileWriter fw= new FileWriter("D:\\testout.txt");
BufferedWriter bw= new BufferedWriter(fw);
bw.write("Welcome to javaTpoint.");
bw.close();
System.out.println("Success");
}
}
40
Using the File Class
Java File Class helps to represent a file type or
directory.
Java file class is mainly used for creating and listing new
directories, it also has many methods to list the common
attributes of files and directories.
43
Name of method Description
getAbsolutePath() Returns the absolute pathname for the abstract pathname.
getFreeSpace() Returns the count of the unallocated bytes in the partition.
Returns the path of the file which is denoted by this
getName()
abstract filename.
This method returns the pathname string of the file which
getParent()
is denoted by this abstract filename’s parent.
This method returns the abstract pathname string of the
getParentFile()
file which is denoted by this abstract filename’s parent.
getPath() Converts the abstract pathname into a pathname.
Check for directory, whether the given pathname is a
isDirectory()
directory or not.
To test whether the given abstract file is a normal file or
isFile()
not.
44
Name of method Description
This method tests whether the file given is
isHidden()
hidden or not.
length() To return length of the file.
Returns an array of strings which has the
String[] list()
names of the files and directories.
Denote the names of the abstract pathnames
File[] listFiles()
in the directory.
mkdir() To create a directory with this name.
renameTo(File To rename the file with this abstract
dest) pathname.
45
Name of method Description
setExecutable(boolean
This method is used to set owner’s executing permission.
executable)
setReadable(boolean This method is used to set an owner’s reading
readable) permission.
46
import java.io.*;
public class demo
{
public static void main(String args[])
{
File f=new File (“a.txt");
System.out.println(“Writable : ” +f.canWrite());
System.out.println(“Readable : ” +f.canRead());
System.out.println(“Hidden: ” +f.isHidden());
System.out.println(“Absolute : ” +f.isAbsolute);
System.out.println(“Directory : ” +f.isDirectory());
System.out.println(“File” +f.isFile());
System.out.println(“Name : ” +f.getName());
System.out.println(“Parent : ” +f.getParent());
System.out.println(“Path: ” +f.getPath());
System.out.println(“Last Modified: ” +f.lastModified());
System.out.println(“Length : ” +f.length());
f.delete();
}
47
I/O Exceptions
Sr No Exceptions Description
48
Handling Primitive Data Types
49
1. DataInputStream Methods -
Method Description
int read() Reads a byte of data from the underlying input stream.
Reads a boolean data from the underlying input
boolean readBoolean()
stream as a 1-byte value.
byte readByte() Reads a byte of data from the underlying input stream.
Reads a character data from the underlying input
char readChar()
stream.
double readDouble() Reads a double data from the underlying input stream.
float readFloat() Reads a float data from the underlying input stream.
int readInt() Reads a integer data from the underlying input stream.
long readLong() Reads a long data from the underlying input stream.
50
1. DataInputStream Methods -
Method Description
Reads a short data from the underlying input
short readShort()
stream.
Reads a unsigned byte from the underlying input
int readUnsignedByte()
stream.
Reads a unsigned short from the underlying input
int readUnsignedShort()
stream.
Returns the number of remaining bytes that can be
int available()
read from the underlying input stream.
Skips over and discards n bytes of data from the
long skip(long n)
input stream.
Closes the stream and releases any system resources
void close()
associated with it.
51
2. DataOutputStream Methods -
Method Description
This method used to write the specified
void write(int b) byte(int to byte) to the underlying output
stream.
This method used to write b.length bytes from
void write(byte[] b) the specified byte array to the underlying
output stream.
This method used to write the
void writeBoolean(boolean v) specified boolean to the underlying output
stream as a 1-byte value.
52
2. DataOutputStream Methods -
Method Description
This method used to write the specified
void writeByte(int v) byte(int to byte) to the underlying output
stream.
This method used to write the specified string
void writeBytes(String s) to the underlying output stream as a sequence
of bytes.
This method used to write the specified char to
void writeChar(int v) the underlying output stream as a 2-byte value,
high byte first.
This method used to write the specified string
void writeChars(String s) to the underlying output stream as a sequence
of characters.
void close() This method used to close the stream.
53
Method Description
This method used to write the specified int to the
void writeInt(int v)
underlying output stream as four bytes, high byte first.
Converts the float argument to an int using the
floatToIntBits method in class Float, and then writes
void writeFloat(float v)
that int value to the underlying output stream as a 4-
byte quantity, high byte first.
Converts the double argument to a long using the
doubleToLongBits method in class Double, and then
void writeDouble(double v)
writes that long value to the underlying output stream
as an 8-byte quantity, high byte first.
This method used to write the specified long to the
void writeLong(long v) underlying output stream as eight bytes, high byte
first.
This method used to write the specified short to the
void writeShort(int v)
underlying output stream as two bytes, high byte first.
54
- END -
55