Delete a file


import java.io.File;

public class Main {
  public static void main(String[] args) {
    String fileName = "file.txt";
    File f = new File(fileName);

    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");
  }
}
Home 
  Java Book 
    Runnable examples  

IO File:
  1. Compare File Dates
  2. Compress files using with ZIP
  3. Concatenate files
  4. Copy a File with NIO FileChannel and ByteBuffer
  5. Copy a file with FileReader and FileWriter
  6. Copy a file with InputStream and OutputStream
  7. Copy a file and overwrite
  8. Delete a file
  9. Delete File Recursively
  10. Get readable file size
  11. Move a file
  12. Rename a file
  13. Report a file's status
  14. Search a file by regular expressions
  15. Touch a file: set File Last Modified Time