Delete file using Java IO API : File Commands : File Input Output : Java examples (example source code) Organized by topic

Java
C++
PHP
Java Home »  File Input Output   » [  File Commands  ]  Screenshots 
 



Delete file using Java IO API

import java.io.File;

public class Delete {
  public static void main(String[] args) {
    String fileName = "file.txt";
    // A File object to represent the filename
    File f = new File(fileName);

    // Make sure the file or directory exists and isn't write protected
    if (!f.exists())
      throw new IllegalArgumentException(
          "Delete: no such file or directory: " + fileName);

    if (!f.canWrite())
      throw new IllegalArgumentException("Delete: write protected: "
          + fileName);

    // If it is a directory, make sure it is empty
    if (f.isDirectory()) {
      String[] files = f.list();
      if (files.length > 0)
        throw new IllegalArgumentException(
            "Delete: directory not empty: " + fileName);
    }

    // Attempt to delete it
    boolean success = f.delete();

    if (!success)
      throw new IllegalArgumentException("Delete: deletion failed");
  }

}

           
       
Related examples in the same category
1.  File Copy in Java
2.  Counts words in a file, outputs results in sorted form
3.  Copying a file using channels and buffers
4.  Copy files using Java IO API Copy files using Java IO API
5.  Mimic the Unix Grep command
6.  File concatenation
7.  Compress files using the Java ZIP API
8.  Undent - remove leading spaces
9.  TeePrintStream tees all PrintStream operations into a file, rather like the UNIX tee(1) command
10.  Delete a file from within Java, with error handling
11.  DirTree - directory lister, like UNIX ls or DOS and VMS dir DirTree - directory lister, like UNIX ls or DOS and VMS dir
12.  Program to empty a directory
13.  Report on a file's status in Java
14.  Simple directory lister
15.  Readonly Files
16.  List root directory List root directory
17.  Rename a file in Java
18.  FNFilter - directory lister using FilenameFilter
19.  mkdir examples
20.  Program to remove files matching a name in a directory
21.  Ls directory lister modified to use FilenameFilter Ls directory lister modified to use FilenameFilter
22.  Dir Stack Dir Stack
23.  Word Count
24.  Diff: text file difference utility. Diff: text file difference utility.
25.  Count chars in a File








Home| Contact Us
Copyright 2003 - 04 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.