0% found this document useful (0 votes)
1 views32 pages

File Handling in Java

Uploaded by

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

File Handling in Java

Uploaded by

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

Java File Class

In this tutorial, we will learn about Java File and its various operations
with the help of examples.

The File class of the java.io package is used to perform various


operations on files and directories.
There is another package named java.nio that can be used to work with
files. However, in this tutorial, we will focus on the java.io package.

File and Directory


A file is a named location that can be used to store related information.
For example,

main.java is a Java file that contains information about the Java


program.
A directory is a collection of files and subdirectories. A directory inside a
directory is known as subdirectory.

Create a Java File Object


To create an object of File, we need to import the java.io.File package
first. Once we import the package, here is how we can create objects of
file.
// creates an object of File using the path
File file = new File(String pathName);

Here, we have created a file object named file. The object can be used
to work with files and directories.

Note: In Java, creating a file object does not mean creating a file.
Instead, a file object is an abstract representation of the file or directory
pathname (specified in the parenthesis).

Java File Operation Methods


Operation Method Package

To create file createNewFile() java.io.File

To read file read() java.io.FileReader

To write file write() java.io.FileWriter

To delete file delete() java.io.File

Java create files

To create a new file, we can use the createNewFile() method. It returns


 true if a new file is created.
 false if the file already exists in the specified location.
Example: Create a new File

// importing the File class

import java.io.*;

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

// create a file object for the current location


File file = new File("newFile.txt");

try {

// trying to create a file based on the object


boolean value = file.createNewFile();
if (value) {
System.out.println("The new file is created.");
}
else {
System.out.println("The file already exists.");
}
}
catch(Exception e) {
e.getStackTrace();
}
}
}

In the above example, we have created a file object named file. The file
object is linked with the specified file path.

File file = new File("newFile.txt");

Here, we have used the file object to create the new file with the
specified path.

If newFile.txt doesn't exist in the current location, the file is created


and this message is shown.
The new file is created.

However, if newFile.txt already exists, we will see this message.

The file already exists.

Java read files

To read data from the file, we can use subclasses of


either InputStream or Reader.
Example: Read a file using FileReader

Suppose we have a file named input.txt with the following content.

This is a line of text inside the file.

Now let's try to read the file using Java FileReader.

// importing the FileReader class


import java.io.FileReader;

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

char[] array = new char[100];


try {
// Creates a reader using the FileReader
FileReader input = new FileReader("input.txt");

// Reads characters
input.read(array);
System.out.println("Data in the file:");
System.out.println(array);

// Closes the reader


input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}

Output

Data in the file:


This is a line of text inside the file.

In the above example, we have used created an object of FileReader


named input. It is now linked with the input.txt file.

FileReader input = new FileReader("input.txt");

To read the data from the input.txt file, we have used the read() method
of FileReader.

Java write to files

To write data to the file, we can use subclasses of


either OutputStream or Writer.
Example: Write to file using FileWriter

// importing the FileWriter class


import java.io.FileWriter;

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

String data = "This is the data in the output file";


try {
// Creates a Writer using FileWriter
FileWriter output = new FileWriter("output.txt");

// Writes string to the file


output.write(data);
System.out.println("Data is written to the file.");

// Closes the writer


output.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}

Output

Data is written to the file.

In the above example, we have created a writer using


the FileWriter class. The writer is linked with the output.txt file.

FileWriter output = new FileWriter("output.txt");

To write data to the file, we have used the write() method.


Here when we run the program, the output.txt file is filled with the
following content.

This is the data in the output file.

Java delete files

We can use the delete() method of the File class to delete the specified
file or directory. It returns
 true if the file is deleted.
 false if the file does not exist.

Note: We can only delete empty directories.

Example: Delete a file

import java.io.File;

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

// creates a file object


File file = new File("file.txt");

// deletes the file


boolean value = file.delete();
if(value) {
System.out.println("The File is deleted.");
}
else {
System.out.println("The File is not deleted.");
}
}
}

Output

The File is deleted.

In the above example, we have created an object of File named file. The
file now holds the information about the specified file.

File file = new File("file.txt");

Here we have used the delete() method to delete the file specified by
the object.
Input-OutputStream : FileInput/OutputStream, BufferedInput/OutputStream,
DataInput/OutputStream
Reader-Writer : FileReader/Writer, BufferedReader/Writer, InputStreamReader,
OutputStreamWriter

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

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


Let's see the code to print output and an error message to the
console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character

OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given
below:

OutputStream
Java application uses an output stream to write data to a destination; it
may be a file, an array, peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source; it
may be a file, an array, peripheral device or socket.

Let's understand the working of Java OutputStream and InputStream by


the figure given below.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all
classes representing an output stream of bytes. An output stream
accepts output bytes and sends them to some sink.

Useful methods of OutputStream

Method Description

1) public void write(int)throws is used to write a byte to the current output


IOException stream.

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 flushes the current output stream.


IOException

4) public void close()throws is used to close the current output stream.


IOException

OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.

Useful methods of InputStream

Method Description

1) public abstract int reads the next byte of data from the input strea
read()throws IOException returns -1 at the end of the file.

2) public int available()throws returns an estimate of the number of bytes tha


IOException be read from the current input stream.

3) public void close()throws is used to close the current input stream.


IOException

InputStream Hierarchy
import java.io.FileInputStream;

public class Main {

public static void main(String args[]) {

try {
FileInputStream input = new FileInputStream("input.txt");

System.out.println("Data in the file: ");

// Reads the first byte


int i = input.read();
while(i != -1) {
System.out.print((char)i);

// Reads next byte from the file


i = input.read();
}
input.close();
}

catch(Exception e) {
e.getStackTrace();
}
}
}

import java.io.FileOutputStream;

public class Main {


public static void main(String[] args) {

String data = "This is a line of text inside the file.";

try {
FileOutputStream output = new
FileOutputStream("output.txt");
byte[] array = data.getBytes();

// Writes byte to the file


output.write(array);

output.close();
}

catch(Exception e) {
e.getStackTrace();
}
}
}

Java BufferedOutputStream Class


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.

For adding the buffer in an OutputStream, use the


BufferedOutputStream class. Let's see the syntax for adding the buffer
in an OutputStream:

1. OutputStream os= new BufferedOutputStream(new FileOutputStream(


"D:\\IO Package\\testout.txt"));

Java BufferedOutputStream class declaration


Let's see the declaration for Java.io.BufferedOutputStream class:

1. public class BufferedOutputStream extends FilterOutputStream


Java BufferedOutputStream class constructors

Constructor Description

BufferedOutputStream(OutputStrea It creates the new buffered output stream w


m os) is used for writing the data to the spe
output stream.

BufferedOutputStream(OutputStrea It creates the new buffered output stream w


m os, int size) is used for writing the data to the spe
output stream with a specified buffer size.

Java BufferedOutputStream class methods

Method Description

void write(int b) It writes the specified byte to the buffered output stream.

void write(byte[] b, It write the bytes from the specified byte-input stream i
int off, int len) specified byte array, starting with the given offset

void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:


In this example, we are writing the textual information in the
BufferedOutputStream object which is connected to
the FileOutputStream object. The flush() flushes the data of one stream
and send it into another. It is required if you have connected the one
stream with another.

1. package com.javatpoint;
2. import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}

Output:

Success

testout.txt

Welcome to javaTpoint.

Java BufferedInputStream Class


Java BufferedInputStream class is used to read information
from stream. It internally uses buffer mechanism to make the
performance fast.

The important points about BufferedInputStream are:

o When the bytes from the stream are skipped or read, the internal
buffer automatically refilled from the contained input stream,
many bytes at a time.
o When a BufferedInputStream is created, an internal
buffer array is created.

Java BufferedInputStream class declaration


Let's see the declaration for Java.io.BufferedInputStream class:

1. public class BufferedInputStream extends FilterInputStream


Java BufferedInputStream class constructors

Constructor Description

BufferedInputStream(InputStrea It creates the BufferedInputStream and sav


m IS) argument, the input stream IS, for later use.

BufferedInputStream(InputStrea It creates the BufferedInputStream with a spe


m IS, int size) buffer size and saves it argument, the input st
IS, for later use.

Java BufferedInputStream class methods

Method Description

int available() It returns an estimate number of bytes that can be read from
input stream without blocking by the next invocation metho
the input stream.

int read() It read the next byte of data from the input stream.

int read(byte[] b, It read the bytes from the specified byte-input stream i
int off, int ln) specified byte array, starting with the given offset.

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

void reset() It repositions the stream at a position the mark method wa


called on this input stream.

void mark(int It sees the general contract of the mark method for the
readlimit) stream.

long skip(long x) It skips over and discards x bytes of data from the input stre
boolean It tests for the input stream to support the mark and
markSupported() methods.

Example of Java BufferedInputStream


Let's see the simple example to read data of file using
BufferedInputStream

package com.javatpoint;

1.
2. import java.io.*;
3. public class BufferedInputStreamExample{
4. public static void main(String args[]){
5. try{
6. FileInputStream fin=new FileInputStream("D:\\testout.txt");
7. BufferedInputStream bin=new BufferedInputStream(fin);
8. int i;
9. while((i=bin.read())!=-1){
10. System.out.print((char)i);
11. }
12. bin.close();
13. fin.close();
14. }catch(Exception e){System.out.println(e);}
15. }
16. }

Here, we are assuming that you have following data


in "testout.txt" file:

javaTpoint

Output:

javaTpoint
Java DataOutputStream Class
Java DataOutputStream class allows an application to write
primitive Java data types to the output stream in a machine-
independent way.

Java application generally uses the data output stream to write data
that can later be read by a data input stream.

Java DataOutputStream class declaration


Let's see the declaration for java.io.DataOutputStream class:

1. public class DataOutputStream extends FilterOutputStream implem


ents DataOutput

Java DataOutputStream class methods

Method Description

int size() It is used to return the number of bytes written to the


output stream.

void write(int b) It is used to write the specified byte to the unde


output stream.

void write(byte[] b, int off, It is used to write len bytes of data to the output strea
int len)

void It is used to write Boolean to the output stream as a 1


writeBoolean(boolean v) value.

void writeChar(int v) It is used to write char to the output stream as a 2


value.

void writeChars(String s) It is used to write string to the output stream


sequence of characters.

void writeByte(int v) It is used to write a byte to the output stream as a 1


value.

void writeBytes(String s) It is used to write string to the output stream


sequence of bytes.

void writeInt(int v) It is used to write an int to the output stream

void writeShort(int v) It is used to write a short to the output stream.

void writeShort(int v) It is used to write a short to the output stream.

void writeLong(long v) It is used to write a long to the output stream.

void writeUTF(String str) It is used to write a string to the output stream using U
encoding in portable manner.

void flush() It is used to flushes the data output stream.

Example of DataOutputStream class


In this example, we are writing the data to a text file testout.txt using
DataOutputStream class.

1. package com.javatpoint;
2.
3. import java.io.*;
4. public class OutputExample {
5. public static void main(String[] args) throws IOException {
6. FileOutputStream file = new FileOutputStream(“D:\\testout.txt”);
7. DataOutputStream data = new DataOutputStream(file);
8. data.writeInt(65);
9. data.flush();
10. data.close();
11. System.out.println("Succcess...");
12. }
13. }

Output:
Succcess...

testout.txt:

Java DataInputStream Class


Java DataInputStream class allows an application to read primitive data
from the input stream in a machine-independent way.

Java application generally uses the data output stream to write data
that can later be read by a data input stream.

Java DataInputStream class declaration


Let's see the declaration for java.io.DataInputStream class:

1. public class DataInputStream extends FilterInputStream implement


s DataInput

Java DataInputStream class Methods

Method Description

int read(byte[] b) It is used to read the number of bytes from the


stream.

int read(byte[] b, int off, int It is used to read len bytes of data from the input str
len)

int readInt() It is used to read input bytes and return an int value.

byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a
value.

double readDouble() It is used to read eight input bytes and returns a d


value.

boolean readBoolean() It is used to read one input byte and return true if b
non zero, false if byte is zero.

int skipBytes(int x) It is used to skip over x bytes of data from the


stream.

String readUTF() It is used to read a string that has been encoded usin
UTF-8 format.

void readFully(byte[] b) It is used to read bytes from the input stream and
them into the buffer array.

void readFully(byte[] b, int It is used to read len bytes from the input stream.
off, int len)

Example of DataInputStream class


In this example, we are reading the data from the file testout.txt file.

1. package com.javatpoint;
2. import java.io.*;
3. public class DataStreamExample {
4. public static void main(String[] args) throws IOException {
5. InputStream input = new FileInputStream("D:\\testout.txt");
6. DataInputStream inst = new DataInputStream(input);
7. int count = input.available();
8. byte[] ary = new byte[count];
9. inst.read(ary);
10. for (byte bt : ary) {
11. char k = (char) bt;
12. System.out.print(k+"-");
13. }
14. }
15. }

Here, we are assuming that you have following data


in "testout.txt" file:

JAVA

Output:

J-A-V-A

Java BufferedReader Class


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. It makes the performance fast. It
inherits Reader class.

Java BufferedReader class declaration


Let's see the declaration for Java.io.BufferedReader class:

1. public class BufferedReader extends Reader

Java BufferedReader class constructors

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

BufferedReader(Reader It is used to create a buffered character input stream


rd, int size) uses 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 It is used for reading characters into a portion of an arra
off, int len)

boolean It is used to test the input stream support for the mar
markSupported() 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


read.

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

void reset() It repositions the stream at a position the mark method


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 sy
resources associated with the stream.

Java BufferedReader Example


In this example, we are reading the data from the text
file testout.txt using Java BufferedReader class.

1. package com.javatpoint;
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);

int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}

Here, we are assuming that you have following data in "testout.txt"


file:

Welcome to javaTpoint.

Output:

Welcome to javaTpoint.

Reading data from console by InputStreamReader


and BufferedReader
In this example, we are connecting the BufferedReader stream with
the InputStreamReader stream for reading the line by line data from
the keyboard.

1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedReaderExample{
4. public static void main(String args[])throws Exception{
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7. System.out.println("Enter your name");
8. String name=br.readLine();
9. System.out.println("Welcome "+name);
10. }
11. }

Output:

Enter your name


Nakul Jain
Welcome Nakul Jain

Another example of reading data from console until


user writes stop
In this example, we are reading and printing the data until the user
prints stop.

1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedReaderExample{
4. public static void main(String args[])throws Exception{
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7. String name="";
8. while(!name.equals("stop")){
9. System.out.println("Enter data: ");
10. name=br.readLine();
11. System.out.println("data is: "+name);
12. }
13. br.close();
14. r.close();
15. }
16. }

Output:

Enter data: Nakul


data is: Nakul
Enter data: 12
data is: 12
Enter data: stop
data is: stop

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

Class declaration

Constructor Description

BufferedWriter(Writer It is used to create a buffered character output stream that


wrt) uses the default size for an output buffer.

BufferedWriter(Writer It is used to create a buffered character output stream that


wrt, int size) uses the specified size for an output buffer.

Let's see the declaration for Java.io.BufferedWriter class:

1. public class BufferedWriter extends Writer


Class constructors

Method Description

void newLine() It is used to add a new line by writing a line


separator.

void write(int c) It is used to write a single character.

void write(char[] cbuf, int off, int It is used to write a portion of an array of
len) characters.

void write(String s, int off, int len) It is used to write a portion of a string.

void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream

Class methods
Example of Java BufferedWriter
Let's see the simple example of writing the data to a text
file testout.txt using Java BufferedWriter.

1. package com.javatpoint;
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to javaTpoint.");
buffer.close();
System.out.println("Success");
}
}
Output:

success

testout.txt:

Welcome to javaTpoint.

Java InputStreamReader
An InputStreamReader is a bridge from byte streams to character
streams: It reads bytes and decodes them into characters using a
specified charset. The charset that it uses may be specified by name or
may be given explicitly, or the platform's default charset may be
accepted.

Constructor

Constructor name Description

InputStreamReader(InputStream in) It creates an InputStreamReader that uses


the default charset.

InputStreamReader(InputStream in, It creates an InputStreamReader that uses


Charset cs) the given charset.

InputStreamReader(InputStream in, It creates an InputStreamReader that uses


CharsetDecoder dec) the given charset decoder.

InputStreamReader(InputStream in, It creates an InputStreamReader that uses


String charsetName) the named charset.

Method

Modifier and Method Description


Type
void close() It closes the stream and releases
system resources associated with it.

String getEncoding() It returns the name of the char


encoding being used by this stream.

int read() It reads a single character.

int read(char[] cbuf, int It reads characters into a portion of an a


offset, int length)

boolean ready() It tells whether this stream is ready


read.

Example
public class InputStreamReaderExample {
public static void main(String[] args) {
try {
InputStream stream = new FileInputStream("file.txt");
Reader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:

I love my country

The file.txt contains text "I love my country" the InputStreamReader


reads Character by character from the file
Java OutputStreamWriter
OutputStreamWriter is a class which is used to convert character
stream to byte stream, the characters are encoded into byte using a
specified charset. write() method calls the encoding converter which
converts the character into bytes. The resulting bytes are then
accumulated in a buffer before being written into the underlying output
stream. The characters passed to write() methods are not buffered. We
optimize the performance of OutputStreamWriter by using it with in a
BufferedWriter so that to avoid frequent converter invocation.

Constructor

Constructor Description

OutputStreamWriter(OutputStream out) It creates an OutputStreamWriter that uses


the default character encoding.

OutputStreamWriter(OutputStream out, It creates an OutputStreamWriter that uses


Charset cs) the given charset.

OutputStreamWriter(OutputStream out, It creates an OutputStreamWriter that uses


CharsetEncoder enc) the given charset encoder.

OutputStreamWriter(OutputStream out, It creates an OutputStreamWriter that uses


String charsetName) the named charset.

Methods

Modifier and Method Description


Type

Void close() It closes the stream, flushing it first.

Void flush() It flushes the stream.


String getEncoding() It returns the name of the character enc
being used by this stream.

Void write(char[] cbuf, int It writes a portion of an array of character


off, int len)

Void write(int c) It writes a single character.

Void write(String str, int off, It writes a portion of a string.


int len)

Example
1. public class OutputStreamWriterExample {
2. public static void main(String[] args) {
3.
4. try {
5. OutputStream outputStream = new FileOutputStream("output.t
xt");
6. Writer outputStreamWriter = new OutputStreamWriter(outputS
tream);
7.
8. outputStreamWriter.write("Hello World");
9.
10. outputStreamWriter.close();
11. } catch (Exception e) {
12. e.getMessage();
13. }
14. }
15. }

Output:

output.txt file will contains text "Hello World"

You might also like