Created
February 9, 2012 14:45
-
-
Save Ramasubramanian/1780442 to your computer and use it in GitHub Desktop.
File helper class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FilenameFilter; | |
import java.util.HashSet; | |
import java.util.List; | |
import java.util.Set; | |
public class FileUtil { | |
private static String getSimpleFileName(final String fileName){ | |
if(fileName == null || fileName.length() == 0) | |
return fileName; | |
final String[] arr = fileName.split(File.separator); | |
return arr[arr.length - 1]; | |
} | |
public static boolean deleteFilesExcept(List<String> fileNames, String folderName){ | |
File folder = new File(folderName); | |
if(!folder.exists() || ! folder.isDirectory() || !folder.canWrite()) { | |
throw new RuntimeException("Folder "+folderName+" is not accessible or is not a directory"); | |
} | |
final Set<String> fNames = new HashSet<String>(); | |
for(String fileName : fileNames) { | |
fNames.add(getSimpleFileName(fileName)); | |
} | |
final File[] filesToDelete = folder.listFiles(new FilenameFilter() { | |
@Override | |
public boolean accept(File dir, String name) { | |
return !fNames.contains(name); | |
} | |
}); | |
for(final File f : filesToDelete) { | |
f.delete(); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment