In this article, we will learn how to work with files and directories in Java. java.io 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.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
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 {

    @Test
    public void createFile(){
        try{

            //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");
            }else{
                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 ");
            writer.flush();
            writer.close();

            if (new File(path).isFile())
            {
                System.out.println("Using isFile - File exists");
            }else{
                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");
            }else{
                System.out.println("Using Path - File does not exist");
            }

            //Read all contents of a file
            System.out.println(Files.readAllLines(path1));

            //deleting a file
            Files.delete(path1);

        }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!!