0% found this document useful (0 votes)
18 views10 pages

OOPJ 4341602 Unit-5 2023

This document covers file handling in Java, focusing on the Java I/O API and stream classes. It explains the types of streams (byte and character), their differences, and provides examples of using various classes such as FileInputStream, FileOutputStream, FileReader, and FileWriter for reading and writing files. Additionally, it includes sample Java programs demonstrating file creation, writing, reading, and appending operations.

Uploaded by

krenishj
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)
18 views10 pages

OOPJ 4341602 Unit-5 2023

This document covers file handling in Java, focusing on the Java I/O API and stream classes. It explains the types of streams (byte and character), their differences, and provides examples of using various classes such as FileInputStream, FileOutputStream, FileReader, and FileWriter for reading and writing files. Additionally, it includes sample Java programs demonstrating file creation, writing, reading, and appending operations.

Uploaded by

krenishj
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
You are on page 1/ 10

Object Oriented Programming with JAVA (4341602)| Unit-5

Unit - V: File handling in Java (CO4) (10 Marks)


File Handling
 Java I/O (Input and Output) is used to process the input and produce the output based on the input.
 Java uses the concept of a stream to make I/O operation fast.
 The java.io package contains all the classes required for input and output operations.
 We can perform file handling in Java by Java I/O API.

 Explain basics of stream classes. 04 – Winter-2023, 2024, Summer-2024


Introduction to Stream
 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. System.out: standard output stream
2. System.in: standard input stream
3. System.err: standard error stream

Types of Stream
 In general, a Stream will be an input stream (source) or, an output stream (destination).
o InputStream − used to read data from a source.
o OutputStream − used to write data to a destination.

 Based on the data they handle there are two types of streams
1. Byte Stream Classes: 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.
2. Character Stream Classes: Using these you can read and write text data only.

Stream Byte Stream Character Stream


Source Stream InputStream Reader
Destination Stream OutputStream Writer

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 1


Object Oriented Programming with JAVA (4341602)| Unit-5
 Difference between Byte Stream and Character Stream:
Sr.
Byte Stream Character Stream
No.
It operates on binary data and data is processed It operates on text data and is processed
1
byte by byte. character by character
Suitable for processing non-textual data such as Suitable for processing textual data such as
2
images, videos, etc. documents, HTML, etc.
Input and Output operations are performed using Input and Output operations are performed using
3
InputStream and OutputStream classes Reader and Writer classes
Suitable for high-level input and output
4 Suitable for low-level input and output operations
operations
Examples include FileInputStream and
5 Examples include FileReader and FileWriter
FileOutputStream
 Explain java I/O process. 04 – Winter-2023
 Explain the different I/O Classes available with Java. 04 - Summer-2023, Winter-2024
Stream classes and its hierarchy

Useful I/O classes


 The Java Input/output (I/O) is a part of Java.io package. The Java.io package contains a relatively large
number of classes that support input and output operations.
 The InputStream and OutputStream are central classes in the package which are used for reading from
and writing to byte streams, respectively.

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 2


Object Oriented Programming with JAVA (4341602)| Unit-5
 InputStreamClass
 Java application uses an input stream to read data from a source, it may be a file, an array, peripheral
device or socket.
 An input stream is automatically opened when you create object of InputStream class.
 You can explicitly close a stream with the close( ) method, or let it be closed implicitly when the object
is found as a garbage.
 Methods

Syntax Description
It reads bytes of data from a stream. If no data is available it blocks the method. When a
read( ) method is blocked, the thread executing waits until the data is available. It rows an
IOExceptionif an error occurs.
available( ) This method returns the number of available bytes that can be read without blockage.
This method closes the input stream. It releases the resources associated with the stream. It
close( )
throws an IOException if an error occurs.
mark( ) This method is used to mark the current position in the stream.
This method repositions the stream to the last marked position. This method throws an
reset( )
IOExceptionif an error occurs.
This method skips n bytes of input.
skip( ) -n is the parameter used which specifies the number of bytes to be skipped. It throws an
IOException if an error occurs.

 OutputStream Class
 Java application uses an output stream to write data to a destination, it may be a file, an array
peripheral device or socket.
 Like an input stream, an output stream is automatically opened when you create an object of
OutputStream class.
 You can explicitly close an output stream with the close( ) method, or let it be closed implicitly when the
object is garbage collected.

Syntax Description
This method writes a byte and throws an IOException if an error occurs. This method actually
write()
blocks until the byte is written. The thread waits until the write operation is been completed.
This method flushes the stream. The buffered data is written to the outputstream. It throws an
flush()
IOException if an error occurs.
This method closes the stream. It is used to release any resource associated with the stream. It
close()
throws an IOException if an error occurs.

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 3


Object Oriented Programming with JAVA (4341602)| Unit-5
File Class
 The File class is an abstract representation of file and directory pathname.
 This class is used for create of files and directories, file searching, file deletion etc.
 A pathname can be either absolute or relative.
File file = new File(String pathname);
 Method of File class:
o createNewFile() – creates a new empty file in Java, and return a Boolean value: true if the file is
created successful; false if the file is already exists or the operation failed. (throws IOException)
o delete() - delete the file or directory.
o getName() – returns the name of file or directory
Example, Write a java program to create a text file
import java.io.File;
import java.io.IOException;
class CreateFileExample1
{
public static void main(String[] args)
{
File file = new File("d:/JAVAProgram/file1.txt");
try {
//creates a new file
if(file.createNewFile()) // test if successfully created a new file
{
System.out.println("file created " + file.getName()); //returns the path string
}
else {
System.out.println("File already exist at location: " + file.getName());
}
}
catch(IOException e)
{
System.out.println("Error..!!!");
}
}
}
Output: file created file1.txt

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 4


Object Oriented Programming with JAVA (4341602)| Unit-5
 Byte Streams
FileOutputStream class
 FileOutputStream is used to create a file and write data into it.
 The OutputStream will only create a file, if it doesn't already exist, before opening it for output.
 There are two way for using file with FileOutputStream.
FileOutputStream f = new FileOutputStream("D:/java/hello.txt");
OR
File f = new File("C:/java/hello.txt");
FileOutputStream f1 = new FileOutputStream( f );

 Write a java program to create a text file and perform write operation on the text file. 07 –
Winter-2023, Summer-2024
Example,
import java.io.*;
public class FileOutExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("d:/JAVAProgram/file1.txt");
String s="Welcome to OOPJ";
byte b[]=s.getBytes(); //converting string into byte array
fout.write(b);
fout.close();
System.out.println("Write in file successfully.");
}
catch(Exception e){ System.out.println(e); }
}
}
Output: Write in file successfully.

FileInputStream class
 FileInputStream is used for reading data from the files.
 While using FileInputStream class, file must already exist if file does not exist it will generate error.
 There are two way for using file with FileInputStream.
FileInputStream f1 = new FileInputStream("D:/java/hello.txt");
OR

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 5


Object Oriented Programming with JAVA (4341602)| Unit-5
File f = new File("D:/java/hello.txt");
FileInputStream f1 = new FileInputStream( f );

 Write a java program to create a text file and perform read operation on the text file. 07 – Winter-
2023, Summer-2023(03)
Example,
import java.io.*;
class FileInExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("d:/JAVAProgram/FileHandling/file2.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}
catch(Exception e){System.out.println(e);}
}
}
Output: Welcome to OOPJ

 Character Streams
FileWriter
 Java FileWriter class is used to write character data to the file.
 Two ways to create FileWriter Object.
FileWriter f = new FileWriter(String fname); //File path is specified in argument.
OR
FileWriter f = new FileWriter(File f1); //1st file is created and it is passed as argument.
 Method of FileWriter Class

void write(int ch) Writing single character to the file.


void write(String s) Writes the string into FileWriter.
void write(char[] c) Writes char array into FileWriter.
void close() Closes FileWriter.

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 6


Object Oriented Programming with JAVA (4341602)| Unit-5
 Write a java program to perform write operation on the text file using FileWriter class. 04
Example,
import java.io.*;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter w=new FileWriter("d:/JAVAProgram/file1.txt");
w.write("Welcome to OOPJ");
w.close();
}
catch(Exception e){System.out.println(e);}
System.out.println("Write in file successfully.");
}
}
Output: Write in file successfully.

FileReader
 Java FileReader class is used to read character data from the file.
 Two ways to create FileReader Object.
FileReader f = new FileReader(String name); //File path is specified in argument.
OR
FileReader f = new FileReader(File f1); //1st file is created and it is passed as argument.
 Method of FileReader Class

int read() Returns a character in ASCII form. It returns -1 at the end of file.
int read(char[] ch) To read data from the file into char array.
void close() Closes FileReader.
 Write a java program to perform read operation on the text file using FileReader class. 04
Example,
import java.io.*;
class FileReaderExample {
public static void main(String args[]){
try{
FileReader r=new FileReader("d:/JAVAProgram/file1.txt");
int i=0;
while((i=r.read())!=-1){

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 7


Object Oriented Programming with JAVA (4341602)| Unit-5
System.out.print((char)i);
}
r.close();
}
catch(Exception e){System.out.println(e);}
}
}
Output: Welcome to OOPJ

 BufferedWriter - BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for providing the efficient
writing of single arrays, characters, and strings.
Example,
import java.io.*;
class BufferedWriterExample {
public static void main(String args[]) throws Exception{
FileWriter writer = new FileWriter("D:/JAVA/FileHandling/file1.txt");
BufferedWriter b = new BufferedWriter(writer);
b.write("Welcome to java.");
b.close();
System.out.println("Write Successfully");
}
}
Output: Write Successfully

 Buffered Reader - 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. It makes the performance fast. It inherits
Reader class.
Example,
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[]){
try{
FileReader r=new FileReader("d:/JAVA/FileHandling/file1.txt");
BufferedReader br=new BufferedReader(r);
int i=0;

Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 8


Object Oriented Programming with JAVA (4341602)| Unit-5
while((i=br.read())!=-1)
{
System.out.print((char)i);
}
br.close();
}catch(Exception e){System.out.println(e);}
}
}
Output: Welcome to java.
 OutputStreamWriter - Output stream that translate character to byte.
 InputStreamReader - Input stream that translate byte to character.
 Write a java program to display the content of a text file and perform append operation on the
text file. 07 – Winter-2023, Summer-2024
import java.io.*;
class FileAppend {
public static void main(String args[]){
try{
FileWriter w=new FileWriter("d:/JAVA/FileHandling/file1.txt",true);
w.write(" subject");
w.close();
}
catch(Exception e)
{System.out.println(e);}
System.out.println("Append in file successfully.");
}
}
Output: Append in file successfully.
 Write a java program to display content of a text file and perform modify operation on text file. 03
import java.io.*;
public class FileModify {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("d:/JAVA/FileHandling/file1.txt");
String s="Welcome to java";
byte b[]=s.getBytes(); //converting string into byte array
fout.write(b);
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 9
Object Oriented Programming with JAVA (4341602)| Unit-5
fout.close();
System.out.println("File Modified");
FileInputStream fin=new FileInputStream("d:/JAVA/FileHandling/file1.txt");
int i=0;
while((i=fin.read())!=-1) {
System.out.print((char)i);
}
fin.close();
}
catch(Exception e){ System.out.println(e);}
}
}
Output:
File Modified
Welcome to java
 Write a program in Java that read the content of a file byte by byte and copy it into another file.
03 - Summer-2023
import java.io.*;
class FileCopy {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("d:/JAVA/FileHandling/file1.txt");
FileOutputStream fout=new FileOutputStream("d:/JAVA/FileHandling/file2.txt");
int i=0;
while((i=fin.read())!=-1){
fout.write(i);
}
fin.close();
fout.close();
}
catch(Exception e){System.out.println(e);}
System.out.println("Copy data file1 to file2");
}
}
Output: Copy data file1 to file2
**********
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 10
inprotected.com

You might also like