So here is my class:
public class FileDeleter implements Deleter {
public void deleteDirectories(List<GroupOfCountries> organizedCountries, String path) {
List<String> listOfThreeLettersGroups = new ArrayList<String>();
for (GroupOfCountries groupedCountries : organizedCountries) {
listOfThreeLettersGroups.add(groupedCountries.getName()); //Here it's adding "ABC" and "PQR" to ArrayList because my countries are Albania, Belgium and Portugal.
}
for (String directoryToDelete : listOfThreeLettersGroups) {
String pathOfGorupDirectory = (path + File.separator + directoryToDelete); //Here it's creating paths to ABC and PQR directories, for example /home/test/ABC
File tempfile = createFile(pathOfGorupDirectory);
deleteDirectory(tempfile);
}
}
protected File createFile(String pathOfGorupDirectory) {
return new File(pathOfGorupDirectory);
}
private boolean deleteDirectory(File dir) {
if (dir.isDirectory()) {
File[] children = dir.listFiles();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDirectory(children[i]);
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
I want to have 100% missed branches. If I comment these lines:
if (!success) {
return false;
}
I have 100% missed branches. But somebody have idea what can I do using mockito/junits to change success into false? Because success always returns true so this if will never happend.
Maybe this will help.
FileDeleter deleter = Mockito.mock(FileDeleter.class);
Mockito.when(deleter.deleteDirectory(Mockito.any())).thenReturn(false);
Related
public static void fileSearcher() throws IOException {
File dire = new File ("C:/");
String[] allFile = dire.list();
for (int i = 0;i<10;i++) {
String FilIn = allFile[i]; // here is where I need to scan entire pc for file
if(FilIn.equals("eclipse.exe")){
System.out.println("Found Eclipse!");
break;
}
else {
System.out.println("Eclipse not found on local drive.");
}
Is there a simple way to scan an entire HHD/SSD for a specific file ?
This will do the job for you and it works too when there are multiple drives or partitions. It will also search for additional files with that same name.
import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class HardDiskSearcher {
private static boolean fileFound = false;
private static String searchTerm = "eclipse.exe";
public static void main(String[] args) {
fileFound = false;
File[] systemRoots = File.listRoots();
FileSystemView fsv = FileSystemView.getFileSystemView();
for (File root: systemRoots) {
if (fsv.getSystemTypeDescription(root).equals("Local Disk")) {
File[] filesFromRoot = root.listFiles();
recursiveSearch(searchTerm, filesFromRoot);
}
}
System.out.println("File you searched for was found? : " + fileFound);
}
private static void recursiveSearch(String searchTerm, File... files) {
for (File file: files) {
if (file.isDirectory()) {
File[] filesInFolder = file.listFiles();
if (filesInFolder != null) {
for (File f : filesInFolder) {
if (f.isFile()) {
if (isTheSearchedFile(f, searchTerm)) {
fileFound = true;
}
}
}
for (File f : filesInFolder) {
if (f.isDirectory()) {
recursiveSearch(searchTerm, f);
}
}
}
}
else if (isTheSearchedFile(file, searchTerm)) {
fileFound = true;
}
}
}
private static boolean isTheSearchedFile(File file, String searchTerm) {
if (file.isFile() && (searchTerm.equals(file.getName())) ) {
System.out.println("The file you searched for has been found! " +
"It was found at: " + file.getAbsolutePath());
return true;
}
return false;
}
}
I am not 100% sure about why the if-statement (filesInFolder != null) is necessary here but i suspect Windows returns null when trying to list files from specific system folder or something.
Can anyone help me to skip file having extension "read" in my code ?
I have two files in my folder:
123.csv
123.csv.read
After execution every csv file is converted into ".csv.read", but if the same file comes again, that file should be skipped.
Like this file (123.csv.read) has been processed already, so if same new file(123.csv) comes, I want to be skipped that file.
In my code below, after 123.csv file is processed, the folder has only one file 123.csv.read. break is not behaving as I was expecting.
context.Str = ((String)globalMap.get("tFileList_1_CURRENT_FILEPATH"));
String extension = context.Str.substring(context.Str.lastIndexOf(".") + 1);
if (extension.equals("read"))
{
break;
}
else {
System.out.println("Good File to Process");
}
public static void listFile(final String folder, final String ext) {
ExtFilter filter = new ExtFilter(ext);
File dir = new File(folder);
if (dir.isDirectory() == false) {
System.out.println("Directory does not exists : " + FindFileExtension.FILE_DIR);
return;
}
// list out all the file name and filter by the extension
String[] list = dir.list(filter);
if (list.length == 0) {
System.out.println("no files end with : " + ext);
return;
}
for (String file : list) {
String temp = new StringBuffer(FindFileExtension.FILE_DIR).append(File.separator).append(file).toString();
System.out.println("file : " + temp);
// do your stuff here this file is not processed
}
}
public static class ExtFilter implements FilenameFilter {
private String ext;
public ExtFilter(final String ext) {
this.ext = ext;
}
public boolean accept(final File dir, final String name) {
return (name.endsWith(this.ext));
}
}
You can do something like that,it might help you
You can try this:
For example 123.csv file came again, then you check this if exist in read folder
if(!new File(123.csv+".read").exist()) {
// if this file is not exist, then it means that this has not been processed
// process the file
} else {
// do some other staff
}
Edit: Or you can try this
public static void main(String[] args) throws Exception {
File dir = new File("your_path");
File[] processedFiles = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().contains("read");
}
});
List<File> files = Arrays.asList(processedFiles);
File[] noneProcessedFiles = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return !pathname.getName().contains("read");
}
});
for (File file : noneProcessedFiles) {
if (!files.stream().findAny().get().getName().contains(file.getName())) {
// process the file....
System.out.println("Not found ... " + file.getName());
} else {
// do some other staff....
System.out.println("Fount the file");
}
}
}
I'd like to write a function that deletes all empty folders, with the option to ignore certain file types (allowed file types are stored in the hashmap) and tell if it should look inside directories.
Calling:
HashMap<String, Boolean> allowedFileTypes = new HashMap<String, Boolean>();
allowedFileTypes.put("pdf", true);
deleteEmptyFolders("ABSOLUTE PATH", allowedFileTypes, true);
Function:
public static void deleteEmptyFolders(String folderPath, HashMap<String, Boolean> allowedFileTypes, boolean followDirectory) {
File targetFolder = new File(folderPath);
File[] allFiles = targetFolder.listFiles();
if (allFiles.length == 0)
targetFolder.delete();
else {
boolean importantFiles = false;
for (File file : allFiles) {
String fileType = "folder";
if (!file.isDirectory())
fileType = file.getName().substring(file.getName().lastIndexOf('.') + 1);
if (!importantFiles)
importantFiles = (allowedFileTypes.get(fileType) != null);
if (file.isDirectory() && followDirectory)
deleteEmptyFolders(file.getAbsolutePath(), allowedFileTypes, followDirectory);
}
// if there are no important files in the target folder
if (!importantFiles)
targetFolder.delete();
}
}
The problem is that nothing is happening, even though it looks through all folders till the end. Is this a good approach or am I missing something completely?
This piece of code recursively delete all the empty folders or directory:
public class DeleteEmptyDir {
private static final String FOLDER_LOCATION = "E:\\TEST";
private static boolean isFinished = false;
public static void main(String[] args) {
do {
isFinished = true;
replaceText(FOLDER_LOCATION);
} while (!isFinished);
}
private static void replaceText(String fileLocation) {
File folder = new File(fileLocation);
File[] listofFiles = folder.listFiles();
if (listofFiles.length == 0) {
System.out.println("Folder Name :: " + folder.getAbsolutePath() + " is deleted.");
folder.delete();
isFinished = false;
} else {
for (int j = 0; j < listofFiles.length; j++) {
File file = listofFiles[j];
if (file.isDirectory()) {
replaceText(file.getAbsolutePath());
}
}
}
}
}
You can use code to delete empty folders using Java.
public static long deleteFolder(String dir) {
File f = new File(dir);
String listFiles[] = f.list();
long totalSize = 0;
for (String file : listFiles) {
File folder = new File(dir + "/" + file);
if (folder.isDirectory()) {
totalSize += deleteFolder(folder.getAbsolutePath());
} else {
totalSize += folder.length();
}
}
if (totalSize ==0) {
f.delete();
}
return totalSize;
}
Shortest code I could come up with is following Java >=8 code:
Files.walk(Paths.get("/my/base/dir/"))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.filter(File::isDirectory)
.forEach(File::delete);
Add a second (or more) filter statement with whatever clause you need to include/exclude certain folders. File::delete should not delete folders with contents.
Use at own risk.
Kotlin:
fun deleteAllEmptyDirectories(rootPath: Path): Collection<Path> =
mutableListOf<Path>()
.apply {
Files.walk(testPath)
.sorted { p1, p2 -> p2.count() - p1.count() }
.map { it.toFile() }
.filter { it.isDirectory }
.forEach {
if (it.listFiles().all { el -> el.isDirectory && contains(el.toPath()) }) {
val path = it.toPath()
add(path)
Files.delete(path)
}
}
}
Test:
private val testPath = Path.of("build", javaClass.simpleName, UUID.randomUUID().toString())
#Test
fun test() {
Files.createDirectory(testPath)
val dirWithTwoEmptySubdirs = Files.createDirectory(testPath.resolve("dirWithTwoEmptySubdirs"))
val dir1 = Files.createDirectory(dirWithTwoEmptySubdirs.resolve("dir1"))
val dir2 = Files.createDirectory(dirWithTwoEmptySubdirs.resolve("dir2"))
val dirWithOneDiffDir = Files.createDirectory(testPath.resolve("dirWithOneDiffDir"))
var emptyDir = Files.createDirectory(dirWithOneDiffDir.resolve("empty"))
val notEmptyDir = Files.createDirectory(dirWithOneDiffDir.resolve("notempty"))
Files.writeString(notEmptyDir.resolve("file.txt"), "asdf")
assertEquals(
setOf<Path>(dirWithTwoEmptySubdirs, dir1, dir2, emptyDir),
deleteAllEmptyDirectories(testPath).toSet()
)
}
After reading all answers and concluding that all of them have at least one problem I still had to write it myself:
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Temp {
public static void main(String[] args) {
final String path = "D:\\";
deleteEmpty(new File(path));
}
private static int deleteEmpty(File file) {
List<File> toBeDeleted = Arrays.stream(file.listFiles()).sorted() //
.filter(File::isDirectory) //
.filter(f -> f.listFiles().length == deleteEmpty(f)) //
.collect(Collectors.toList());
int size = toBeDeleted.size();
toBeDeleted.forEach(t -> {
final String path = t.getAbsolutePath();
final boolean delete = t.delete();
System.out.println("Deleting: \t" + delete + "\t" + path);
});
return size;
}
}
I want to return a file list from a function which loops through all the files/directories on SD card on android and which confirm the specific data type(mp3, mp4, png). But I cannot figure out when to return the values from the loop. Can anyone help me with this?
My code:
private Pattern patternVideo = Pattern.compile("([^\\s]+(\\.(?i)(mp4))$)");
private Pattern patternAudio = Pattern.compile("([^\\s]+(\\.(?i)(mp3))$)");
private Pattern patternImages = Pattern
.compile("([^\\s]+(\\.(?i)(png|jpeg|jpg))$)");
Matcher videoMatcher, audioMatcher, imageMatcher;
private ArrayList<String> videoFiles = new ArrayList<String>();
private ArrayList<String> audioFiles = new ArrayList<String>();
private ArrayList<String> imageFiles = new ArrayList<String>();
private void buildFileList(File dirName) {
if (dirName.isFile()) {
// matcher = pattern.matcher(dirName.getName());
// if (matcher.find())
// fileNamesWithPaths.add(dirName.getAbsolutePath());
} else if (dirName.isDirectory()) {
File[] files = dirName.listFiles();
for (File file : files) {
if (file.isFile()) {
videoMatcher = patternVideo.matcher(file.getName());
audioMatcher = patternAudio.matcher(file.getName());
imageMatcher = patternImages.matcher(file.getName());
if (videoMatcher.find()) {
videoFileNames.add(file.getAbsolutePath());
} else if (audioMatcher.find()) {
audioFileNames.add(file.getAbsolutePath());
} else if (imageMatcher.find()) {
imageFileNames.add(file.getAbsolutePath());
}
} else if (file.isDirectory()) {
buildFileList(file);
}
}
}
}
Just put your return statement outside of the isDirectory() test:
private ArrayList buildFileList(File dirName) {
if (dirName.isDirectory()) {
File[] files = dirName.listFiles();
for (File file : files) {
if (file.isFile()) {
videoMatcher = patternVideo.matcher(file.getName());
audioMatcher = patternAudio.matcher(file.getName());
imageMatcher = patternImages.matcher(file.getName());
if (videoMatcher.find()) {
videoFiles.add(file.getAbsolutePath());
} else if (audioMatcher.find()) {
audioFiles.add(file.getAbsolutePath());
} else if (imageMatcher.find()) {
imageFiles.add(file.getAbsolutePath());
}
} else if (file.isDirectory()) {
buildFileList(file);
}
}
}
//Combine your arrayLists here
return CombinedLists //return the Combined Lists
}
You don't need to return anything; after the call the three *Files lists will have all the files you seek.
Edit: why won't you use the MediaStore provider?
Using Stack will help you to avoid recursion:
private void buildFileList(File dirName) {
Stack<File> stack = new Stack<File>();
stack.add(dirName);
while(!stack.isEmpty()){
File next = stack.pop();
if (next.isFile()) {
// do something...
} else if (next.isDirectory()) {
stack.addAll(Arrays.asList(next.listFiles()));
}
}
}
I need a to find file according to its name in directory tree. And then show a path to this file. I found something like this, but it search according extension. Could anybody help me how can I rework this code to my needs...thanks
public class filesFinder {
public static void main(String[] args) {
File root = new File("c:\\test");
try {
String[] extensions = {"txt"};
boolean recursive = true;
Collection files = FileUtils.listFiles(root, extensions, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
File root = new File("c:\\test");
String fileName = "a.txt";
try {
boolean recursive = true;
Collection files = FileUtils.listFiles(root, null, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
if (file.getName().equals(fileName))
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Recursive directory search in Java is pretty darn easy. The java.io.File class has a listFiles() method that gives all the File children of a directory; there's also an isDirectory() method you call on a File to determine whether you should recursively search through a particular child.
You can use FileFilter Like this.
public class MyFileNameFilter implements FilenameFilter {
#Override
public boolean accept(File arg0, String arg1) {
// TODO Auto-generated method stub
boolean result =false;
if(arg1.startsWith("KB24"))
result = true;
return result;
}
}
And call it like this
File f = new File("C:\\WINDOWS");
String [] files = null;
if(f.isDirectory()) {
files = f.list(new MyFileNameFilter());
}
for(String s: files) {
System.out.print(s);
System.out.print("\t");
}
Java 8 Lamda make this easier instead of using FileNameFilter, pass lambda expression
File[] filteredFiles = f.listFiles((file, name) ->name.endsWith(extn));
I don't really know what FileUtils does, but how about changing "txt" in extenstions to "yourfile.whatever"?
public static File find(String path, String fName) {
File f = new File(path);
if (fName.equalsIgnoreCase(f.getName())) return f;
if (f.isDirectory()) {
for (String aChild : f.list()) {
File ff = find(path + File.separator + aChild, fName);
if (ff != null) return ff;
}
}
return null;
}