In this article, we will learn how to work with files and directories in Java. and java.nio package contains all classes and interfaces required for working with files in Java. We can read and write from the files using FileInputStream and FileOutputStream classes respectively. Below code will illustrate how to work with files in Java and perform basic things like checking if file exists, how to create, delete files, get more information about files in Java and read contents of file.

package corejava;

import org.junit.Test;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

 * Created by Sagar on 10-04-2016.
public class files {

    public void createFile(){

            //check if file exists
            String path = "f1.txt";

            File f = new File(path);
            if(f.exists() && !f.isDirectory()) {
                System.out.println("Using exists - File exists");
                System.out.println("Using exists - File does not exist");

            //append to file. Create a file if not exists
            FileWriter writer = new FileWriter(f,true);
            writer.append("Hello ");

            if (new File(path).isFile())
                System.out.println("Using isFile - File exists");
                System.out.println("Using exists - File does not exist");

            Path path1 = Paths.get(path);
            if (Files.exists(path1) && !Files.isDirectory(path1)) {
                System.out.println("Using Path - File exists");
                System.out.println("Using Path - File does not exist");

            //Read all contents of a file

            //deleting a file

        }catch (IOException ex){

Here is the output of above example.

Using exists – File does not exist
Using isFile – File exists
Using Path – File exists
[Hello ]

Web development and Automation testing

solutions delivered!!