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
Java Book
Runnable examples
IO File:
- Compare File Dates
- Compress files using with ZIP
- Concatenate files
- Copy a File with NIO FileChannel and ByteBuffer
- Copy a file with FileReader and FileWriter
- Copy a file with InputStream and OutputStream
- Copy a file and overwrite
- Delete a file
- Delete File Recursively
- Get readable file size
- Move a file
- Rename a file
- Report a file's status
- Search a file by regular expressions
- Touch a file: set File Last Modified Time