Tuesday, October 27, 2015

Delete files in a Directory?

/**
     * Delete file
     *
     * @param filePath
     */
    public void deleteFile(String filePath) throws Exception {
        try {
            File file = new File(filePath);

            if (file.delete()) {
                System.out.println(file.getName() + " is deleted..!");
            }
        } catch (Exception e) {
            throw new Exception(">>>Error while deleting " + filePath + " file :<<<" + e.toString());
        }
    }
 
public void deleteFilesFromFolder(File directoryPath) {
        String[] myFiles;
        if (directoryPath.isDirectory()) {
            myFiles = directoryPath.list();
            for (int i = 0; i < myFiles.length; i++) {
                File myFile = new File(directoryPath, myFiles[i]);
                myFile.delete();
            }
        }
    }

EX: File directoryPath = new File("C:\\Example");

No comments:

Post a Comment