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

Chapter 06

The document provides an overview of managing input and output (I/O) files in Java, focusing on the java.io package and its stream classes. It explains the concepts of byte and character streams, detailing classes like InputStream, OutputStream, FileReader, and FileWriter, along with their methods and usage examples. Additionally, it covers the File class for file manipulation and the benefits of buffered streams for performance enhancement.

Uploaded by

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

Chapter 06

The document provides an overview of managing input and output (I/O) files in Java, focusing on the java.io package and its stream classes. It explains the concepts of byte and character streams, detailing classes like InputStream, OutputStream, FileReader, and FileWriter, along with their methods and usage examples. Additionally, it covers the File class for file manipulation and the benefits of buffered streams for performance enhancement.

Uploaded by

sanikakabade07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

6.

Managing I/O Files in Java

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.

Though internally FileReader uses FileInputStream and FileWriter uses


FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
3
Stream Classes – Byte Stream Classes –
W14,S16,18
 The use of Byte Stream Classes is to read data and write
data in byte format from an input and output stream
respectively.
 Categorized in 2 groups –
1. InputStream Classes: These classes are extended from
InputStream which is an abstract class. These classes are
used to read bytes from a source such as file, memory or
console.
2. OutputStream Classes: These classes are extended from
OutputStream which is an abstract class. These classes
are used to write bytes into source such as file, memory
or console. 4
Stream Classes – Byte Stream Classes

5
Stream Classes – Byte Stream Classes

6
Byte Stream Classes – 1. InputStream Class

 InputStream class is a base class of all the classes that are


used to read bytes from a file, memory or console.

 InputStream is an abstract class and hence we can't create


its object but we can use its subclasses for reading bytes
from the input stream.

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

 OutputStream class is a base class of all the classes that


are used to write bytes to a file, memory or console.

 OutputStream is an abstract class and hence we can't


create its object but we can use its subclasses for writing
bytes to the output stream.

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

flush() Flushesh the output stream and clears the buffer.

This method writes byte (contained in an int) to the


abstract write(int c)
output stream.

This method writes a whole byte array(b) to the


write(byte[] b)
output.

This method closes this output stream and also frees


close()
any resources connected with this output stream.
12
Byte Stream Classes – Example

Class Description

ByteArrayInputStream contains methods to read bytes from


a byte array.

ByteArrayOutputStream Contains methods to write bytes into


a byte array.

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*/

out.close(); //closing the stream


}
}
15
Creation of Files
 The File class from the java.io package, allows us to work with
files.
 To use the File class, create an object of the class, and specify the
filename or directory name:

import java.io.File; // Import the File class

File f = new File("filename.txt"); // Specify the filename

OR

File f= new File("/usr/local/bin/filename.txt");

16
Reading/Writing Bytes
Reading/Writing Bytes

1. FileInputStream

2. FileOutputStream

3. BufferedInputStream
&
BufferedOutputStream

17
Reading/Writing Bytes : 1. FileInputStream

 java.io.FileInputStream reads byte stream from a file


system.
 It has three constructors :

1. FileInputStream(File file) : Accepts file object

2. FileInputStream(FileDescriptor fd) : Accepts


filedescriptor object

3. FileInputStream(String name) : Accepts file path as string

18
Reading/Writing Bytes : 1. FileInputStream

 Methods of FileInputStream Class – S15,W15,W17

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 :

1. FileOutputStream(File file) : Accepts file object


2. FileOutputStream(FileDescriptor fd) : Accepts
filedescriptor object
3. FileOutputStream(String name) : Accepts file path as string
4. FileOutputStream(File file, boolean append) : Accepts file
object and a Boolean variable to append.
5. FileOutputStream(String name, boolean append) : Accepts
file path as string and a boolean variable to append.
22
Reading/Writing Bytes : 2. FileOutputStream

 Methods of FileOutputStream Class

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 internally uses buffer mechanism to make the performance fast.

 Java BufferedOutputStream class is used for buffering an output


stream. It internally uses buffer to store data.

 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");

BufferedOutputStream bout=new BufferedOutputStream(fout);


String s="Welcome to java.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
} Write a String
catch(Exception e) using
{
System.out.println(e);
BufferedOutputStream
28
}}}
Stream Classes – Character Stream Class – s16
 Character Streams − These handle data in 16 bit Unicode. Using
these you can read and write text data only.
 The Reader and Writer classes (abstract) are the super classes of all
the character stream classes: classes that are used to read/write
character streams.
 Following are the character array stream classes provided by Java −

Reader (Input) Writer (Output)


BufferedReader BufferedWriter
CharacterArrayReader CharacterArrayWriter
StringReader StringWriter
FileReader FileWriter
29
Stream Classes – Character Stream Class

30
Reading/Writing Characters
Reading/Writing Characters
1. FileReader &
FileWriter

2. charArrayReader &
charArrayWriter

3. BufferedReader &
BuferedWriter

31
Reading/Writing Characters : 1. FileReader & FileWriter

 Java FileReader class is used to read data from the file.

 Java FileWriter class is used to write character-oriented


data to a file. It is character-oriented class which is used
for file handling in java.

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

 CharArrayReader class and CharArrayWriter class


implement a character buffer that can be used as a
character-input stream and character- output stream
respectively.

 Invoking close() method of the CharArrayReader class


and CharArrayWriter class have no effect.

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

 Java BufferedReader class is used to read the text from


a character-based input stream. It can be used to read data
line by line by readLine() method.

 Java BufferedWriter class is used to provide buffering


for Writer instances. It makes the performance fast.

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.

 file and directory are not the same, a directory is the


parent folder and inside that directory, there is a file.

 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.

 It is also used for file searching, file deletion, renaming a


file, etc.
41
Using the File Class – Constructors of File Classes

1. File (File parent, String child)


It is used to create a new file instance which is derived from
an abstract parent abstract pathname and child pathname
string.

2. File (String pathname)


It is used to convert the denoted pathname string into an
abstract pathname and thus create a new file instance.

3. File (String parent, String child)


It is used to create a new file instance using a parent and
child pathname.
42
Using the File Class – Methods of File Class
W14, W15, S17

Name of method Description


Used to test whether the denoted file can be executed
canExecute()
by the application using this abstact pathname.
Test whether the denoted file can be read using this
canRead()
abstract pathname.
Used to test whether the file denoted can be modified
canWrite()
using this pathname or not.
Automatically creates a new file which is empty with
createNewFile()
this username.

delete() Deletes the file which has this pathname.

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.

Set the directory named so that only read permissions are


setReadOnly()
given.

setWritable(boolean Set the directory named so that only writing permissions


writable) are given.

lastModified() Returns last modification date and time.

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

These are the signals that an attempt to open


1 FileNotFoundException the file denoted by a specified pathname has
failed.

This is a base class for character conversion


2 CharConversionException
exceptions.

These are signals that an end of file or end


3 EOFException of stream has been reached unexpectedly
during input.

4 UnsupportedEncodingException This character encoding is not supported.

This is a superclass of all exceptions


5 ObjectStreamException
specific to Object Stream classes.

48
Handling Primitive Data Types

1. DataInputStream : Reads primitive data from a file


through an input stream which machine independent.

2. DataOutputStream : Write primitive data in a file as


output stream.
Data input stream can then read it back.

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

You might also like