Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Thursday, October 5, 2023

File Handeling in java


We may work with files in Java by using the File Class. This File Class is contained within the java.io package. To utilize the File class, first create an object of the class and then give the name of the file.


Program 1: Create a new file.

import java.io.File;  // Import the File class

import java.io.IOException;  // Import the IOException class to handle errors


public class java88 {

  public static void main(String[] args) {

    try {

      File myObj = new File("myfile.txt");

      if (myObj.createNewFile()) {

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

      } else {

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

      }

    } catch (IOException e) {

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

      e.printStackTrace();

    }

  }

}






Program 2: Write the content in the file.


import java.io.FileWriter;   // Import the FileWriter class

import java.io.IOException;  // Import the IOException class to handle errors


public class java88 {

  public static void main(String[] args) {

    try {

      FileWriter myWriter = new FileWriter("myfile.txt");

      myWriter.write("Writting in Files using JAVA is very simple.");

      myWriter.close();

      System.out.println("Successfully wrote to the file.");

    } catch (IOException e) {

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

      e.printStackTrace();

    }

  }

}






Program 3: Reading the data from files:

import java.io.File;  // Import the File class

import java.io.FileNotFoundException;  // Import this class to handle errors

import java.util.Scanner; // Import the Scanner class to read text files


public class java88  {

  public static void main(String[] args) {

    try {

      File myObj = new File("filename.txt");

      Scanner myReader = new Scanner(myObj);

      while (myReader.hasNextLine()) {

        String data = myReader.nextLine();

        System.out.println(data);

      }

      myReader.close();

    } catch (FileNotFoundException e) {

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

      e.printStackTrace();

    }

  }

}

Output:




No comments:

Post a Comment