GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Private Policy
  • Contact
  • Java
  • Java Core
  • Java Lambda Expression
  • Java Fundamentals
  • Java Stream
  • Java Tools
  • Java XML
  • Jakarta EE
  • CDI
  • JSON Binding
  • JSON Processing
  • MVC

This view

  • Original page
  • New address

GeezerVison is showing huongdanjava.com — Delete file in Java - Huong Dan Java

Khanh Nguyen

I love Java and everything related to Java.

Follow

Share this post

Tags

  • Java File
  • Java Files
  • Java Path
  • Java Paths
Views: 1,139

Even though creating a file in Java is easy, deleting a file is easier. In this tutorial, I will guide you how to delete a file in Java.

The File object, which is the main file management object since Java version 6 and earlier, cannot be ignored.

In this object, we can use the delete() method to delete any file. The condition to delete a file is that: the file must exist on your computer.

Using this method will return a boolean value, true if we delete successfully, otherwise, if the value is false then surely the error occurs.

Java
1
2
3
4
5
6
7
8
9
public class FileDeletion {
    public static void main(String[] args) {
        File file = new File("E:\\note.txt");
        if (file.exists() && file.delete()) {
            System.out.println("File deleted successfully");
        }
    }
}

If you do not use the File object, you can also use the Files object introduced since Java 7. This object provides us with a method called delete() to delete any file.

Java
1
2
3
4
5
6
7
8
9
10
11
12
public class FileDeletion {
    public static void main(String[] args) {
        try {
            Path path = Paths.get("E:\\test.txt");
            Files.delete(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



You might also like...

  • What is a Database Transaction? ACID, JDBC & Isolation Levels

    What is a Database Transaction? ACID, JDBC & Isolation Levels

  • What is JDBC? JDBC Architecture, Driver, Connection, Statement & PreparedStatement | Java

    What is JDBC? JDBC Architecture, Driver, Connection, Statement & PreparedStatement | Java

  • Java Primitive Data Types Part 2 | float, double, boolean

    Java Primitive Data Types Part 2 | float, double, boolean

  • Java Primitive Data Types Part 1 | byte, short, int, long, char & Type Conversion

    Java Primitive Data Types Part 1 | byte, short, int, long, char & Type Conversion

Previous Post: Create file in Java
Next Post: Using ApplicationContextAware and BeanNameAware in Spring

Add Comment Cancel reply

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.