Pin It

How to create and delete a file in Java 7 using java.nio ?

Program to implement how to create and delete a file in Java 7 using java.nio ?.

package com.hubberspot.java7;

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

public class CreateAndDeleteFile {

 public static void main(String[] args) {

  // Create a path to the file which is
  // to be created and deleted later
  // here "D:\\books\\java\\" is the address 
  // to reach the file created by name "hubberspot.java" 
  Path filePath = Paths.get("D:\\books\\java\\hubberspot.java");

  // First we check whether file already exists
  // at the filePath by using Files class static
  // method by name exists()
  if (!Files.exists(filePath)) {

   try {

    // Second we create a file at 
    // the specified filePath by using
    // Files class createFile() method.
    Files.createFile(filePath);

   } catch (IOException e) {

    e.printStackTrace();
   }
  }

  // In order to delete there must be a file,
  // here we check whether file already exists
  // at the filePath by using Files class static
  // method by name exists()
  if (Files.exists(filePath)) {

   try {

    // here we delete a file at 
    // the specified filePath by using
    // Files class delete() method.
    Files.delete(filePath);

   } catch (IOException e) {

    e.printStackTrace();
   }
  }
 }
}



Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot