File handling in java

             Files are essentials in software implementation. File handling deals with creation of a file, reading the contents of a file, writing the contents to a file and deleting a file.

Built in package in java which supports the file operations is “java.io”.

How to implement the file operations in java?

There are four operations in file handling listed as follows.

 1.    Creating a file

 2.    Reading the contents in a file

 3.   Writing the contents to a file

 4.    Deleting a file

1.Creating a file in java:

              It includes the below steps.

Steps:

  • Include the builtin packages.
  • Create a  class with main() function. from the File, create a object myFile1.
  • Using the object, call the createNewFile() function.

import java.io.File;

import java.io.IOException;

public class NewFileCreation {

    public static void main(String[] args) {

        try {

            File myFile1 = new File("newfile.txt");

            if (myFile1.createNewFile()) {

                System.out.println("File created: " + myFile1.getName());

            } else {

                System.out.println("File already exists.");

            }

        } catch (IOException e) {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

}

Output:

C:\raji\blog>javac NewFileCreation.java

C:\raji\blog>java NewFileCreation

File created: abc.txt

2. Reading the contents in a file:

  •  First create contents to the file “abc.txt”. For example,"This file is created by NewFileCreation.java".
  • This program has two reader. One is for FileReader and another one is BufferedReader.
  • FileReader object reads  the file “abc.txt” and store it to bufferedReader object.
  • Using a while loop, the data is read from file and displayed in the output screen.

Program:

import java.io.FileReader;

import java.io.BufferedReader;

import java.io.IOException;

public class ReadIt {

    public static void main(String[] args) {

        try {

            FileReader myReader1 = new FileReader("abc.txt");

            BufferedReader bufferedReader1 = new BufferedReader(myReader1);

            String data;

            while ((data = bufferedReader1.readLine()) != null) {

                System.out.println(data);

            }

            bufferedReader1.close();

        } catch (IOException e) {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

}

Here is the output.

C:\raji\blog>javac ReadIt.java

C:\raji\blog>java ReadIt

"This file is created by NewFileCreation.java"

These are the creation and reading the contents from file using java. Keep Coding!!!

No comments:

Post a Comment