Saturday, January 24, 2015

java.nio.file.FileAlreadyExistsException | java.nio.file.NoSuchFileException

Trying to create multiple directories using the createDirectory() method will throw a NoSuchFileException. Instead use the createDirectories() method. 

Trying to create a directory that already exists will throw a FileAlreadyExistsException. i.e running the same code used to create a single directory more than once on the same path/filename.
See Code Snippet below.

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.FileSystems;       
import java.nio.file.Files;
import java.io.IOException;
import static java.lang.System.err;

public class OcpPrepare {
    public static void main(String[] args) {
    
     //-----------First Part-----------//
    //trying to create multiple direcotries One, Two and Three
        Path newDir = FileSystems.getDefault().getPath("C:\\Users\\", "One\\Two\\Three");      
        try{
        Files.createDirectory(newDir);
        }
        catch(IOException e){
            err.println(e); //NoSuchFileException Thrown ;; 
        }
//-----------Second Part-----------//
//trying to create a directory that already exist
        Path newDir = FileSystems.getDefault().getPath("C:\\Users\\One");      
        try{
        Files.createDirectory(newDir);
        }
        catch(IOException e){
            err.println(e); //FileAlreadyExistsException Thrown ;; 
        }
    }
}

Comapring 2 Paths Using java.nio.file Class

Using Java.nio.file.Path and Paths class

when comparing 2 paths using the equals() method in java "nio.2", one thing to know 4Sure is that, it does not affect the file System, so, therefore, the compared paths are not required to exist. #Very Funny right? See the below sample code snippet
--------------------------------------
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.lang.System.out;

public class OcpPrepare {


    public static void main(String[] args) {

        
      Path firstPath = Paths.get("c:\\users\\Book1.txt");
      Path secondPath = Paths.get("c:\\users\\Book2.txt");
      
      if (firstPath.equals(secondPath))
      {
          out.println("Same Path");
      }
       else
          {
          out.println("Not Same Path");
          }
    }
}