Write a Java Program to Delete File in Java

Java Program to Delete File in Java

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Delete File in Java
Java Program to Delete File in Java

Write a Java Program to Delete File in Java

PROGRAM: Java Program to Delete File in Java

/*Java Program to Delete File in Java*/

1: Java Program to Delete a file using delete()

import java.io.File;

class Main {
public static void main(String[] args) {

// creates a file object
File file = new File(“JavaFile.java”);

// deletes the file
boolean value = file.delete();
if(value) {
System.out.println(“JavaFile.java is successfully deleted.”);
}
else {
System.out.println(“File doesn’t exit”);
}
}
}

2: Java Program to Delete a file using deleteIfExists()

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

class Main {
public static void main(String[] args) {

try {
// creates a file object
Path path = Paths.get(“JavaFile.java”);

// deletes the file
boolean value = Files.deleteIfExists(path);
if(value) {
System.out.println(“JavaFile.java is successfully deleted.”);
}
else {
System.out.println(“File doesn’t exit”);
}
} catch (Exception e) {
e.getStackTrace();
}

}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *