File Handling

One this page you can find a simple guide to reading and writing files in the Java programming language. The code examples here give you everything you need to read ,write ,delete files etc .

1.   Create a File
2.   Read a File
3.   Write a File
4.   Delete a File
5.   List all Filenames in a folder
6.   List Filenames with specific Extension
7.   Create a Folder
8.   Delete a Folder
9.   Move a File from one Folder to another

Create a File



Example

import java.io.File;
import java.io.IOException;
 
public class CreateaFile {
	public static void main(String[] args) {
		try {
			//Set the path of file to be created
			// In this case Code.txt file will be created in path C:/Javaseleniumworld
			File file = new File("C:/Javaseleniumworld/Code.txt");
 
			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
 
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


Read a File


File is read using FileReader (for text files)  wrapped in  BufferedFileReader. This improves performance as it saves up data so you can deal with it a line at a time or whatever instead of character by character.

Example 

 import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFromFile {

	public static void main(String a[]){
		//Set the BufferredReader object to null intitally
		BufferedReader br = null;
		String strLine = "";
		try {
			//Point the br object to the file you want to read 
			//File to be read line by line - C:/Javaseleniumworld/Code.txt
			br = new BufferedReader( new FileReader("C:/Javaseleniumworld/Code.txt"));
			//Read the file Line by Line till Null value is encountered
			while( (strLine = br.readLine()) != null){
				//display each line
				System.out.println(strLine);
			}
		} catch (FileNotFoundException e) {
			//Display error message if File was not found
			System.err.println("Unable to find the file");
		} catch (IOException e) {
			//Display error message if an exception is encounterd while reading the file
			System.err.println("Unable to read the file");
		}
	}
}

Write a File

File is written using  FileWriter  wrapped in  BufferedFileWriter for text files .

Example

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
 
public class WritetoFile {
	public static void main(String[] args) {
		try {
			//String to written in the file - C:/Javaseleniumworld/Code.txt
			String content = "Hello JavaSeleniumWorld.com"; 
			File file = new File("C:/Javaseleniumworld/Code.txt");
 
			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
			//Use BufferedWriter to write to the file
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();
 

		} catch (IOException e) {
			//Display error message if an exception is encounterd while writing the file
			e.printStackTrace();
		}
	}
}

Delete a File

Example

import java.io.File;
 
public class DeleteFileExample
{
    public static void main(String[] args)
    {	
    	try{
    		//File to be deleted - C:/Javaseleniumworld/Code.txt
     		File file = new File("C:/Javaseleniumworld/Code.txt");
 
    		if(file.delete()){
    			System.out.println(file.getName() + " is deleted!");
    		}else{
    			System.out.println("Delete operation is failed.");
    		}
 
    	}catch(Exception e){ 
    		e.printStackTrace(); 
    	}
     }
}

List all Filenames in a Folder

Example

import java.io.File;

public class ListfilesinFolder {	     
	    public static void main(String a[]){
	    	//Set the path of folder for which you wish to list name of all the files stored
	        File file = new File("C:/Javaseleniumworld/");
	        // Object files contains all the files under the selected folder
	        File[] files = file.listFiles();
	        //for each file in the folder
	        for(File f: files){
	            System.out.println(f.getName());
	        }
	    }
	}

List filenames with specific extension

Example

import java.io.File;

public class Listfileswithspecificextension {	     
	    public static void main(String a[]){
	    	//Set folder path for which you wish to get name of the files stored with specific Extension
	        File file = new File("C:/Javaseleniumworld/");
	        // Object files contains all the files under the selected folder
	        File[] files = file.listFiles();
	        //for each file in the folder
	        for(File f: files){
	        	//capture all filenames with .zip extension
	        	//You can mention .txt for extracting files wth .txt extension
	        	if(f.getName().toLowerCase().endsWith(".zip")){
	              //Print the filename with .zip extension
	              System.out.println(f.getName());
	        	}
	        }
	    }
	}


Create Folder



Example 

import java.io.File;

public class CreateaFolder {
  public static void main(String[] args) {
	//Set the path of Folder to be created
	// In this case Folder Javaseleniumworld will be created in path C:
    File file = new File("C:/Javaseleniumworld");
    //If the folder doesnot exist then create it
	if (!file.exists()) {
		if (file.mkdir()) {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
		}
	}
  }
}

Example 

 

import java.io.File;
 
public class CreateFolderstructure{
    public static void main(String[] args){
    	//Set the path of Folders to be created
    	//In this case Folder Javaseleniumworld ,Sub1,Sub2 doesnot exist
    	//The below code will create the Folder Javaseleniumworld and the Subdirectories Sub1 and Sub2
		File files = new File("C:/Javaseleniumworld/Sub1/Sub2");
		if (!files.exists()) {
			if (files.mkdirs()) {
				System.out.println("Multiple directories are created!");
			} else {
				System.out.println("Failed to create multiple directories!");
			}
		}
	 
    }
}


Delete Folder



Example 

import java.io.File;

public class DeleteaFolder {

   public static void main(String[] args){
	   //Set the folder for which delete folder ,all the sub folder and it contents
	   File filez = new File("C:/Javaseleniumworld");
	   deleteFolder(filez);
   }
   
   	 //Function to recursively delete all the sub folder and it contents
	  public static void deleteFolder(File folder) {
		    File[] files = folder.listFiles();
		    if(files!=null) { //some JVMs return null for empty dirs
		        for(File f: files) {
		            if(f.isDirectory()) {
		                deleteFolder(f);
		            } else {
		                f.delete();
		            }
		        }
		    }
		    folder.delete();
		}
  }


Move File from one folder to another



Example 

import java.io.File;
public class MoveFiletoanotherDirectory {
    public static void main(String[] args){
    	//Move the file from  - C:/Javaseleniumworld/Code.txt to - C:/QTPworld/Code.txt
		File from = new File("C:/Javaseleniumworld/Code.txt");
		File to = new File("C:/QTPworld/Code.txt");
		//Rename
		if (from.renameTo(to))
			System.out.println("Successfully Moved the file");
		else
			System.out.println("Error while moving the file");                      

	}
 }