Read, Write and Delete File in Java With Examples

We will be discussing File-based I/O in this lecture. The overall lecture will be divided into the following sections:

  • Create a file
  • Write a file
  • Append a file
  • Read a file
  • Delete a file

Create a File

In order to create a file, we need to import File and IOException class from package java.io. The constructor of File accepts the name(along with its location). The method used to create a file is createNewFile().

Declaration: boolean createNewFile() throws IOException

The return type is boolean. Upon successful creation of the file, it returns true. false indicates that the file with the same name already exists at the mentioned location. The IOException needs to be handled or mentioned as throws in case of the method.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ClassFile{
     //This creates a file
	 public static File createFile(String name) throws IOException{
	  File myFile = new File(name);
	  if(myFile.createNewFile()){
		  System.out.println("The file has been created successfully.");
	  }
	  else{
		  System.out.println("The file already exists.");
	  }
	  return myFile;
  }

	public static void main(String[] args){
		String fileName="DemoFile.txt";
		try {
			File myFile = createFile(fileName);
		}
		catch (IOException e) {
			System.out.println("An IO Exception occurred.");
			e.printStackTrace();
		}
	}
}

Output:

The file has been created successfully.

Write To a File

we will use the write() method of  FileWriter to write some text to the file we created in the example above. After writing, we need to close the FileWriter using close().

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ClassFile{
     //This creates a file
	 public static File createFile(String name) throws IOException{
	  File myFile = new File(name);
	  if(myFile.createNewFile()){
		  System.out.println("The file has been created successfully.");
	  }
	  else{
		  System.out.println("The file already exists.");
	  }
	  return myFile;
     }
    
     //This writes to a file
     public static void writeToFile(String name, String dataToWrite) throws IOException{
		FileWriter myFile = new FileWriter(name);
		myFile.write(dataToWrite);
		myFile.close();
		System.out.println("Successfully wrote to a file.");
	} 

	public static void main(String[] args){
		String fileName="DemoFile.txt";
		try {
			File myFile = createFile(fileName);
            writeToFile(fileName,"Hello\n");
		}
		catch (IOException e) {
			System.out.println("An IO Exception occurred.");
			e.printStackTrace();
		}
	}
}

Output:

The file has been created successfully.
Successfully wrote to a file.

Append to a file

The FileWriter class can also be used to write character-oriented data to a file. We will use the constructor FileWriter(File file, boolean append) constructs a FileWriter object given a File object in append mode. It is a character-oriented class that is used for file handling in Java.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ClassFile{
     //This creates a file
	 public static File createFile(String name) throws IOException{
	  File myFile = new File(name);
	  if(myFile.createNewFile()){
		  System.out.println("The file has been created successfully.");
	  }
	  else{
		  System.out.println("The file already exists.");
	  }
	  return myFile;
     }
    
     //This writes to a file
     public static void writeToFile(String name, String dataToWrite) throws IOException{
		FileWriter myFile = new FileWriter(name);
		myFile.write(dataToWrite);
		myFile.close();
		System.out.println("Successfully wrote to a file.");
	} 

     //This appends str to the file at location fileName
     public static void appendStrToFile(String fileName,String str) throws IOException{  
		BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));//It means the file is open with append permission
		out.write(str); 
		out.close(); 
		System.out.println("Successfully appended to a file.");
	} 
	public static void main(String[] args){
		String fileName="DemoFile.txt";
		try {
			File myFile = createFile(fileName);
            writeToFile(fileName,"Hello\n");
            appendStrToFile(fileName,"I am the appended line");
		}
		catch (IOException e) {
			System.out.println("An IO Exception occurred.");
			e.printStackTrace();
		}
	}
}

 Output:

The file has been created successfully.
Successfully wrote to a file.
Successfully appended to a file.

Read a File

In order to read the file, we will be using the Scanner class. The object of it will accept input from the specified file and will continue to be used until it reaches the end.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ClassFile{
     //This creates a file
	 public static File createFile(String name) throws IOException{
	  File myFile = new File(name);
	  if(myFile.createNewFile()){
		  System.out.println("The file has been created successfully.");
	  }
	  else{
		  System.out.println("The file already exists.");
	  }
	  return myFile;
     }
    
     //This writes to a file
     public static void writeToFile(String name, String dataToWrite) throws IOException{
		FileWriter myFile = new FileWriter(name);
		myFile.write(dataToWrite);
		myFile.close();
		System.out.println("Successfully wrote to a file.");
	} 

     //This appends str to the file at location fileName
     public static void appendStrToFile(String fileName,String str) throws IOException{  
		BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));//It means the file is open with append permission
		out.write(str); 
		out.close(); 
		System.out.println("Successfully appended to a file.");
	} 

    //It is used to read the data from specified file
	public static void readFromFile(File myFile) throws FileNotFoundException {
		Scanner myReader=new Scanner(myFile);
		System.out.println("\nInitiating File Reading....");
		while(myReader.hasNextLine()) {
			System.out.println(myReader.nextLine());
		}
		myReader.close();
	}
	public static void main(String[] args){
		String fileName="DemoFile.txt";
		try {
			File myFile = createFile(fileName);
            writeToFile(fileName,"Hello\n");
            appendStrToFile(fileName,"I am the appended line");
			readFromFile(myFile);
		}
        catch (FileNotFoundException e) {
			System.out.println("An error occurred.");
			e.printStackTrace();
	    }
		catch (IOException e) {
			System.out.println("An IO Exception occurred.");
			e.printStackTrace();
		}
	}
}

Output:

The file has been created successfully.
Successfully wrote to a file.
Successfully appended to a file.

Initiating File Reading....
Hello
I am the appended line

Delete a File

We will be using delete() method of File object to delete the file.

Declaration: boolean delete()

It returns true if and only if the file or directory is successfully deleted else false.

package myFilePackage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ClassFile{
     //This is used to create a file with given name at mentioned path 
	 public static File createFile(String name) throws IOException{
	  File myFile = new File(name);
	  if(myFile.createNewFile()){
		  System.out.println("The file has been created successfully.");
	  }
	  else{
		  System.out.println("The file already exists.");
	  }
	  return myFile;
  }
	//This is used to write dataToWrite to the file at specified path 
	public static void writeToFile(String name, String dataToWrite) throws IOException{
		FileWriter myFile = new FileWriter(name);
		myFile.write(dataToWrite);
		myFile.close();
		System.out.println("Successfully wrote to a file.");
	}  
    //This is used to append str to the file at specified path
	public static void appendStrToFile(String fileName,String str) throws IOException{  
		BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));//It means the file is open with append permission
		out.write(str); 
		out.close(); 
		System.out.println("Successfully appended to a file.");
	}  
	//This is used to read the specified file
	public static void readFromFile(File myFile) throws FileNotFoundException {
		Scanner myReader=new Scanner(myFile);
		System.out.println("\nInitiating File Reading....");
		while(myReader.hasNextLine()) {
			System.out.println(myReader.nextLine());
		}
		myReader.close();
	}
	
	//This is used to delete the specified file
	 public static File deleteFile(File myFile){
		  if(myFile.delete()){
			  System.out.println("The file has been removed successfully.");
		  }
		  else{
			  System.out.println("The file does not exists.");
		  }
		  return myFile;
	  }

	public static void main(String[] args){
		String fileName="DemoFile.txt";
		try {
			File myFile = createFile(fileName);
			writeToFile(fileName,"Hello\n");
			appendStrToFile(fileName,"I am the appended line");
			readFromFile(myFile);
			deleteFile(myFile);
		}
		catch (FileNotFoundException e) {
			System.out.println("An error occurred.");
			e.printStackTrace();
	    }
		catch (IOException e) {
			System.out.println("An IO Exception occurred.");
			e.printStackTrace();
		}
	}
}

Output:

The file has been created successfully. 
Successfully wrote to a file. 
Successfully appended to a file. 

Initiating File Reading.... 
Hello 
I am the appended line

The file has been removed successfully.

This was all about File-based I/O. We will be discussing transient and instanceOf keywords in the next lecture.