File Handling in Java

File Handling in JAVA

File handling is used to store the output in the file so that we see them later. All the console programming is done on RAM and as you close the IDE the whole data is destroyed but what if we need that data later? We use file handling for this purpose.

In file handling, we can read and also write data in files.

import*; is used to access FileWriter and Reader.

FileWriter class in JAVA:

This class is used to save or write any type like text or decimal into the files.


The FileWriter has two type of constructor one will take the path like in above example, and other is for string, and we pass the string in that constructor.

Functions of FileWriter:

  • void write(String text)

Write String data in file

  • void write(char c)

Write Char data in file

  • void close()

Use to close files.


Writing Content to the File

FileReader class in JAVA:

In Java, FileReader is used to read data from files. The FileReader returns data in the forms of bytes.


FileReader filer=new FileReader(“ijk.txt”);

It also has two types of constructor one take string and other take file path.

Functions of FileReader:

  • int read()

It returns a character in ASCII form. If data in file end then it returns -1.

  • int close()

It closes File reader.


Reading Content of the File:

Now if we want to read from one file and write it to another file then the solution is following: