Sunday 27 March 2016

Java NIO - Part 2


Operations on File using Java NIO: Java NIO provides easy mechanism for File copying, moving and deleting. Let's try it out with a basic java program:



package com.bpjoshi.javapriest.iotutorials.nio2;

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

/**
 * @author Bhagwati Prasad (Joshi)
 */
/*
 * Operations On File- Copy, Move and Delete
 *1: Copying Content of a file in another file.
 *2. Deleting a File
 *3. Moving a File
 */
public class JavaNIO3 {
 public static void main(String[] args) throws IOException {
  //1:
  Path source=Paths.get("H:", "Tutorials", "JavaNio", "nio.txt");
  Path target=Paths.get("H:", "Tutorials", "JavaIO", "abcd.txt");
  try{
  Files.copy(source, target);
  }catch(Exception ex){
   ex.printStackTrace();
  }
  
  //2:
  Files.delete(target);
  
  //3:
  Files.move(source, target);
  
 }
 
}



In the code above , if you copy another file from another source to target file, it gives FileAlreadyExistsException. To deal with this, java provides an optional third parameter while copying. For example
Files.copy(source2, target, StandardCopyOption.REPLACE_EXISTING);


This will replace this replace the existing file.  What happens when you try to delete a file that 
doesn't exist. It will throw NoSuchFileException. But java is very careful, it also provides you 
with another method which is Files.deleteIfExists(path). It returns false, if the file doesn't
exist.



3 comments:

  1. wow sir..i m just became your fan and beleieve me i ll try many blog but your one is best

    thank you keep posting

    ReplyDelete
  2. Hey Anand! Thank you for your valuable feedback.

    ReplyDelete
  3. really awesome sir
    its very helpful and easy to learn step by step

    ReplyDelete

Please write your views