how to read and write to a file in java code example

Example 1: writing to a file in java

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

public class WriteToFile {
  public static void main(String[] args) {
    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

Example 2: Java program to write to text file

// Java program to write to text file
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteIntoTextFile 
{
   public static void main(String[] args)
   {
      try
      {    
         FileWriter fw = new FileWriter("B:\\demo.txt");    
         fw.write("Hello World");    
         fw.close();    
      }
      catch(Exception ex)
      {
         System.out.println(ex);
      }    
      System.out.println("Successful");
   }
}

Example 3: creating file in java

package FileHandling;
 
 // Import the File class
import java.io.File;
 
// Import the IOException class to handle errors
import java.io.IOException; 
 
public class CreateFile {
public static void main(String[] args) {
try {
// Creating an object of a file
File myObj = new File("D:FileHandlingNewFilef1.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();
}
}
}

Tags:

Java Example