0% found this document useful (0 votes)
5 views12 pages

File Handleing

The document provides a comprehensive overview of file handling in Java, detailing the java.io package and its classes such as File, FileWriter, and BufferedReader. It explains the concepts of byte and character streams, their differences, and various methods for reading and writing data to files. Additionally, it includes code examples demonstrating the use of these classes for file operations.
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)
5 views12 pages

File Handleing

The document provides a comprehensive overview of file handling in Java, detailing the java.io package and its classes such as File, FileWriter, and BufferedReader. It explains the concepts of byte and character streams, their differences, and various methods for reading and writing data to files. Additionally, it includes code examples demonstrating the use of these classes for file operations.
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/ 12

Package java.io java.io.

File(class file)
public class File extends Object

Interoperability with package

The java.io.file package defines interfaces and classes for the Java virtual machine to access files, file
attributes, and file systems. This API may be used to overcome many of the limitations of
the java.io.File class. The toPath method may be used to obtain a Path that uses the abstract path
represented by a File object to locate a file. The resulting Path may be used with the Files class to
provide more efficient and extensive access to additional file operations, file attributes, and I/O
exceptions to help diagnose errors when an operation on a file fails.

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.

Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods. If you have knowledge about both of them, you can skip it.

Stream:
A series of data is referred to as a stream. In Java, Stream is classified into two types, i.e., Byte
Stream and Character Stream.

Streams in Java
● In Java, a sequence of data is known as a
stream.
● This concept is used to perform I/O
operations on a file.
● There are two types of streams :

Byte Stream
Byte Stream is mainly involved with byte
data. A file handling process with a byte
stream is a process in which an input is
provided and executed with the byte data.

This stream is used to read or write byte data.


The byte stream is again subdivided into two
types which are as follows:

● Byte Input Stream: Used to read byte data from different devices.
● Byte Output Stream: Used to write byte data to different devices.
Character Stream
Character Stream is mainly involved with character data. A file handling process with a
character stream is a process in which an input is provided and executed with the character data.

This stream is used to read or write character data. Character stream is again subdivided into 2 types
which are as follows:

● Character Input Stream: Used to read character data from different devices.
● Character Output Stream: Used to write character data to different devices.

Byte Stream Vs Character Stream In Java :

Byte Stream Character Stream

They process the data byte by byte. They process the data character by character.

They read/write data 8 bits maximum at a time. They read/write data 16 bits maximum at a time.

They are most suitable to process binary files. They are most suitable to process text files.

All byte stream classes in Java are descendants of All character stream classes in Java are
InputStream and OutputStream. descendants of Reader and Writer.

InputStream Class Methods


Method Description

int read() This method returns an integer, an integral representation of the next
available byte of the input. The integer -1 is returned once the end of the
input is encountered.

int read (byte buffer []) This method is used to read the specified buffer length bytes from the
input and returns the total number of bytes successfully read. It returns -1
once the end of the input is encountered.

int read (byte buffer [], This method is used to read the 'nBytes' bytes from the buffer starting at
int loc, int nBytes) a specified location, 'loc'. It returns the total number of bytes successfully
read from the input. It returns -1 once the end of the input is encountered.

int available () This method returns the number of bytes that are available to read.

Void mark(int nBytes) This method is used to mark the current position in the input stream until
the specified nBytes are read.

void reset () This method is used to reset the input pointer to the previously set mark.

long skip (long nBytes) This method is used to skip the nBytes of the input stream and returns
the total number of bytes that are skipped.

void close () This method is used to close the input source. If an attempt is made to
read even after the closing, IOException is thrown by the method.

OutputStream Class Methods

Method Description

write(int b) This method returns an integer, an integral representation of the next


available byte of the input. The integer -1 is returned once the end of the
input is encountered.

write (byte buffer []) This method is used to read the specified buffer length bytes from the
input and returns the total number of bytes successfully read. It returns -1
once the end of the input is encountered.

flash() forces to write all data present in output stream to the destination
void close () This method is used to close the input source. If an attempt is made to
read even after the closing, IOException is thrown by the method.

Reader Class Methods

Constructor Description

Reader() Creates a new character-stream reader whose critical sections will


synchronize on the reader itself.

Reader(Object lock) Creates a new character-stream reader whose critical sections will
synchronize on the given object.

Methods Description

close() Closes the stream and releases any system resources associated with
it.

read() Reads a single character.

read(char[] cbuf) Reads characters into an array.

read(char[] cbuf, int off, Reads characters into a portion of an array.


int len)

read(CharBuffer target) Attempts to read characters into the specified character buffer.

Writer Class Methods

Constructor Description

Writer() Creates a new character-stream writer whose critical sections will


synchronize on the writer itself.

Writer(Object lock) Creates a new character-stream writer whose critical sections will
synchronize on the given object.
Methods Description

close() Closes the stream, flushing it first.

write(int c) Writes a single character.

write(char[] cbuf) Writes an array of characters.

write(char[] cbuf, int off, Writes a portion of an array of characters.


int len)

write(String str) Writes a string.

flush() Flushes the stream.

append(char c) Appends the specified character to this writer.

append(CharSequenc Appends the specified character sequence to this writer.


e csq)

Constructor Summary
File(File parent, String child)
Creates a new File instance from a parent abstract pathname and a child pathname string.

File(String pathname)
Creates a new File instance by converting the given pathname string into an abstract pathname.

File(String parent, String child)


Creates a new File instance from a parent pathname string and a child pathname string.

File(URI uri)
Creates a new File instance by converting the given file: URI into an abstract pathname.
Fil
e
W
rit
e
FileWriter Class Example:

import java.io.FileWriter;
import java.io.IOException;
public class file_writer{
public static void main(String[] args) {
//FileWriter fw=new FileWriter("test.txt");
try{
//if file not exist then FileWriter() create on in drive
FileWriter fw=new FileWriter("test.txt");
fw.write("Amit "); //write as string
fw.write('F'); //write single character
fw.write('I'); //write character on buffered memory
fw.write('E'); //so that it will not reflect at once
fw.write('M'); //flush() method used to store data
buffer to in a specified file
fw.flush(); //so we need to use flush() method
fw.write(" SONARPUR");
fw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

Output: Create a test.txt file on current path and written on that file

Amit FIEM SONARPUR

BufferedWriter Class: Java 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.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

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

File fp=new File("testout.txt");


try{
FileWriter file = new FileWriter(fp);
BufferedWriter buffer = new BufferedWriter(file);
buffer.write("Welcome to java.");
buffer.flush();
buffer.close();
System.out.println("Success");
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Programing running...");
}
}

Output: Create a testout.txt file on current path and written on that file

Welcome to java.

after that on screen will show

Success
Programming running...
Java PrintWriter class

Java PrintWriter class is the implementation of Writer class. It is used to print the formatted
representation of objects to the text-output stream.
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;

public class print_writer{


public static void main(String[] args) {
File file=new File("testPrintWrite.txt");
try{
PrintWriter writer = new PrintWriter(file);
writer.write("Java provides of all technology.");
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}

Output: Create a testPrintWrite.txt file on current path and written on that file Java
provides of all technology.

File Read

Java
FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class. It is character-oriented class which is used for file handling in java.

FileReader in Java is a class in the java.io package which can be used to read a stream of
characters from the files. Java IO FileReader class uses either specified charset or the
platform’s default charset for decoding from bytes to characters.

Hierarchical Flow of FileReader Class

Constructors of FileReader class

Constructor Description

FileReader(String file) It gets filename in string. It opens the given file in read mode. If file
doesn't exist, it throws FileNotFoundException.

FileReader(File file) It gets filename in file instance. It opens the given file in read mode.
If file doesn't exist, it throws FileNotFoundException.

Methods of FileReader class

Method Description

int read() It is used to return a character in ASCII form. It returns -1 at the end of file.

void close() It is used to close the FileReader class.


Java BufferedReader Class
Reads text from a character-input stream, buffering characters so as to provide for the efficient
reading of characters, arrays, and lines. The buffer size may be specified, or the default size
may be used. The default is large enough for most purposes. In general, each read request
made by a Reader causes a corresponding read request to be made of the underlying character
or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose
read() operations may be costly, such as FileReaders and InputStreamReaders. Programs that
use DataInputStreams for textual input can be localized by replacing each DataInputStream with
an appropriate BufferedReader.
It can be used to read data line by line by readLine() method. It makes the performance fast. It
inherits Reader class.

Java BufferedReader class constructors

Constructor Description

BufferedReader(Reader rd) It is used to create a buffered character input stream that uses
the default size for an input buffer.

BufferedReader(Reader rd, It is used to create a buffered character input stream that uses
int size) the specified size for an input buffer.

Java BufferedReader class methods

Method Description

int read() It is used for reading a single character.

int read(char[] cbuf, int off, It is used for reading characters into a portion of an array.
int len)

boolean markSupported() It is used to test the input stream support for the mark and reset
method.

String readLine() It is used for reading a line of text.


boolean ready() It is used to test whether the input stream is ready to be read.

long skip(long n) It is used for skipping the characters.

void reset() It repositions the stream at a position the mark method was last
called on this input stream.

void mark(int It is used for marking the present position in a stream.


readAheadLimit)

void close() It closes the input stream and releases any of the system
resources associated with the stream.

You might also like