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.
wow sir..i m just became your fan and beleieve me i ll try many blog but your one is best
ReplyDeletethank you keep posting
Hey Anand! Thank you for your valuable feedback.
ReplyDeletereally awesome sir
ReplyDeleteits very helpful and easy to learn step by step