Programming Pandit

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


Latest Update

Thursday, September 25, 2025

Reading and Writing Files in JAVA

 /*

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("gk.docx");

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();

    }

  }

}


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("Writing 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();

    }

  }

}


*/

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("myfile.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();

    }

  }

}


No comments:

Post a Comment