Here you can find the source of delete(File file)
Parameter | Description |
---|---|
file | The file or directory. |
Parameter | Description |
---|---|
IOException | For IO Errors. |
public static void delete(File file) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.IOException; public class Main { private static final File[] EMPTY_FILE_ARRAY = new File[0]; /**/*from w w w . java 2s.c o m*/ * Delete a file or directory. * * @param file * The file or directory. * @throws IOException * For IO Errors. */ public static void delete(File file) throws IOException { if (file.isDirectory()) { deleteDir(file); } else { deleteFile(file); } } /** * Delete a directory and all of its contents. * * @param dir * The directory. * @throws IOException * If something cannot be deleted. */ public static void deleteDir(File dir) throws IOException { if (!dir.exists()) { return; } File[] files = listFiles(dir); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { deleteDir(file); } else { deleteFile(file); } } dir.delete(); } /** * Delete file. * * @param file * The file. * @throws IOException * If the file was not deleted. */ private static void deleteFile(File file) throws IOException { boolean success = file.delete(); if (!success) { throw new IOException("Could not delete " + file); } } /** * Utility method to list files but return an empty array instead of null for no results. * * @param dir * The directory. * @return The array of files. */ public static File[] listFiles(File dir) { File[] files = dir.listFiles(); if (files == null) { files = EMPTY_FILE_ARRAY; } return files; } }