I'm creating a java program which takes parent path and deletes all the files and folders in the given path. I'm able to delete files and folder's files inside another folder in the parent folder but not able to delete folders at 3rd level.
Here's my code:
package com.sid.trial;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
public class DeleteFilesOfDirectoryWithFilters {
public static void main(String[] args) {
String parentPath = "D:\\tester";
List<String> folderPaths = deleteFiles(parentPath);
deleteFolders(folderPaths);
}
public static void deleteFolders(List<String> folderPaths) {
for(String path : folderPaths){
File folder = new File(path);
if(folder.delete())
System.out.println("Folder "+folder.getName()+" Successfully Deleted.");
}
}
public static List<String> deleteFiles(String path){
File folder = new File(path);
File[] files = folder.listFiles();
List<String> folderPaths = new ArrayList<String>();
String folderPath = path;
if(files.length == 0){
System.out.println("Directory is Empty or No FIles Available to Delete.");
}
for (File file : files) {
if (file.isFile() && file.exists()) {
file.delete();
System.out.println("File "+file.getName()+" Successfully Deleted.");
} else {
if(file.isDirectory()){
folderPath = file.getAbsolutePath();
char lastCharacter = path.charAt(path.length()-1);
if(!(lastCharacter == '/' || lastCharacter == '\\')){
folderPath = folderPath.concat("\\");
}
/*folderPath = folderPath.concat(file.getName());*/
System.out.println(folderPath);
folderPaths.add(folderPath);
}
}
}
for(String directoryPath : folderPaths){
List<String> processedFiles = new ArrayList<String>();
processedFiles = deleteFiles(directoryPath);
folderPaths.addAll(processedFiles);
}
return folderPaths;
}
}
You can use the ""new"" Java File API with Stream API:
Path dirPath = Paths.get( "./yourDirectory" );
Files.walk( dirPath )
.map( Path::toFile )
.sorted( Comparator.comparing( File::isDirectory ) )
.forEach( File::delete );
Note that the call to sorted() method is here to delete all files before directories.
About one statement, and without any third party library ;)
You should consider using Apache Commons-IO. It has a FileUtils class with a method deleteDirectory that will recursively delete.
Note: Apache Commons-IO (as for version 2.5) provides utilities only for legacy java.io API (File and friends), not for Java 7+ java.nio API (Path and friends).
You can recursively traverse through the folder and delete each file one by one. After deleting all the files in one folder, delete the folder. Something similar to following code should work:
public void delete(File path){
File[] l = path.listFiles();
for (File f : l){
if (f.isDirectory())
delete(f);
else
f.delete();
}
path.delete();
}
You can do the following, your recursion is longer than needed.
public static void deleteFiles (File file){
if(file.isDirectory()){
File[] files = file.listFiles(); //All files and sub folders
for(int x=0; files != null && x<files.length; x++)
deleteFiles(files[x]);
}
else
file.delete();
}
Explanation:
When invoke deleteFiles() on a file, the else statement gets triggered, the single file will be deleted with no recursion.
When invoke deleteFiles() on a folder, the if-statement gets triggered.
Get all the entries (files of folders residing in the folder) as an array
If there exist sub-entries, for each entry, recursively delete the sub-entry (the same process (1 and 2) repeats).
Be careful when implementing deletion of file and folders. You may want to print out all the files and folders name first instead of deleting them. Once confirmed it is working correctly, then use file.delete().
Related
So I'm trying to make a student attendance by reading text files(all files are filled with names of students) from a folder[main folder is named Attendance], which folder has 2 sub-folders, and my program is not showing any text file, below is the code where I've created a File where, the path of the main folder is saved, and then created a List to store all files :
File folder = new File("C:\\Users\\HP\\IdeaProjects\\AdaptiveJava\\src\\StudentAttendance\\Attendance");
List<File> allFiles = Arrays.asList(folder.listFiles());
and so I have a method to print all text files that are inside the main folder :
public static void printFileNames(List<File> fileList){
for(int i = 0; i < fileList.size();i++){
if(fileList.get(i).isFile()){
System.out.println(fileList.get(i).getName());
}
}
}
but is not printing anything, but when I change the file path e.g to
File folder = new File("C:\\Users\\HP\\IdeaProjects\\AdaptiveJava\\src\\StudentAttendance\\Attendance\\SubFolder1");
it prints all text files that are inside sub-folder and vice versa.
What am I doing wrong here? How should multiple text-files be read from sub-folders?
You should also list the files in the subfolder, the method listFiles() only list the files relative to the folder you are in, so you can iterate over the first list of files and then list the files for each subfolder, this is an approach using java 8 streams:
List<File> allFiles = Arrays.stream(folder.listFiles())
.filter(File::isDirectory)
.flatMap(f -> Arrays.stream(f.listFiles()))
.collect(Collectors.toList());
You can also accomplish that using a for to iterate over the result of the first listFiles call, and call that method for every of the files asking first if it's a directory, something like this:
List<File> allFiles = new ArrayList<>();
for (File f : folder.listFiles()) {
if (f.isDirectory()) {
allFiles.addAll(Arrays.asList(f.listFiles()));
}
}
Your code should work. If i use the following code, it prints all filenames in the subfolder filesToPrint of the current working directory.
package test.print.files;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class PrintFiles
{
public static void main(String[] args)
{
File folder = new File("./filesToPrint");
List<File> allFiles = Arrays.asList(folder.listFiles());
printFileNames(allFiles);
}
public static void printFileNames(List<File> fileList)
{
for (int i = 0; i < fileList.size(); i++)
{
if (fileList.get(i).isFile())
{
System.out.println(fileList.get(i).getName());
}
}
}
}
example directory:
c:\filesToPrint\file1.txt
file2.txt
output:
file1.txt
file2.txt
I have a folder called "all_users" in my java project under the src directory.How can I access the files(if there are any) in the all_users folder. I eventually want to loop through all the existing files in the "all_users" folder, comparing whether the file name is equal to a string i specify in the code.
Firstly, I tried File f = new File(System.getProperty("user.home")+File.pathSeparator + "all_users"); as the file object then later tried File dir = new File(TEST_PATH); Both returned false when i checked if it existed so i didn't set up the path correctly?
public class ValUtility {
static final String TEST_PATH = "./all_users/";
public static boolean validUsername(String user) {
File f = new File(System.getProperty("user.home") + File.pathSeparator + "all_users");
File dir = new File(TEST_PATH);
File[] directoryListing = f.listFiles();
System.out.println(f.exists());
System.out.println(directoryListing);
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
// think child is filename?
if (user.equals(child.getName())){
return false;
}
}
}
return true;
}
}
Please run...
System.out.println(System.getProperty("user.home"));
The above will inform you where you need to add a folder labeled 'all_users'. It is very unlikely that your 'user.home' property is set to your project's source file (src) folder.
I want to get the name of the folders from directory who only have .c and .h files.
below is my code but I am not getting that how exactly I can get the folder names who only have .c and .h files.
File directory = new File(directoryName);
//get all the files from a directory
if(directory.exists()){
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isDirectory()){
System.out.println(file.getName());
System.out.println(file.getAbsolutePath());
}
Above code will take the input path for directory and prints the name of all sub folders or sub directories if the main directory is exist.and also prints the path.Now I only want the name of all sub folders from directory which have .c and .h files.
Thanks If anyone help me.
Try to take a look at Apache's DirectoryScanner
Using that we can mention the file extension types to be considered/omitted
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"*.c", "*.h"});
https://ant.apache.org/manual/api/org/apache/tools/ant/DirectoryScanner.html
You can use a list and getParent() function like:
List<String> list;
File directory = new File(directoryName);
if(directory.exists()){
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isDirectory()){
System.out.println(file.getName());
if(file.getName().contains(".c") || file.getName().contains(".h"))
list.add(file.getParent());
System.out.println(file.getAbsolutePath());
}
}
}
for(String item : list) {
System.out.println(item);
}
I've given a pure Java solution here, but if your directory structure is too deep or directories have thousands of files, this may not work out. In that case you may have to run an OS command and dump the output into Java. For instance if you use Unix (or Unix-based) system, you can use find to list directories and invoke the command from Java using ProcessBuilder.
Now the Java solution:
Create a custom FileNameFilter first. This will filter files based on extensions you pass.
public class ExtensionFilter implements FilenameFilter {
private String[] extensions;
public ExtensionFilter(String... extensions) {
this.extensions = extensions;
}
#Override
public boolean accept(File dir, String name) {
for (String extension : extensions) {
if ( name.toLowerCase().endsWith(extension.toLowerCase()) ) {
return true;
}
}
return false;
}
}
Create a FileFilter to help you filter for only directories (for recursion)
public class FolderFilter implements FileFilter {
#Override
public boolean accept(File path) {
return path.isDirectory();
}
}
Use recursion to build list of folder paths contains files with the given extension.
private static final FolderFilter folderFilter = new FolderFilter();
public List<String> recursiveSearch(File base, ExtensionFilter extFilter) {
List<String> paths = new ArrayList<>();
//Does current directory itself have files of given extension?
if (base.list(extFilter).length > 0) {
paths.add(base.getPath()); //Use base.getName() here instead, for just name
}
// Recurse through current directory's subfolders
for (File dir : base.listFiles(folderFilter)) {
paths.addAll(recurse(dir, extFilter));
}
return paths;
}
Finally, invoke it like so:
String basePath = "...";
File baseDir = new File(basePath);
ExtensionFilter extFilter = new ExtensionFilter(".c",".h");
List<String> folders = recurse(baseDir, extFilter);
This will now contain all paths (or names as mentioned above) of folders which have files with given extensions.
I have a folder in a directory. I know, there is always only one file and it's a .txt file. But I don't know the filename.
How can I access it in Java? How must the path look like?
You could open the directory and go over its contents until you find the file:
public static File getTextFileInDirectory(String dirPath) {
File dir = new File(dirPath);
for (File f : dir.listFiles()) {
if (f.isFile() && f.getName().endsWith(".txt")) {
return f;
}
}
return null;
}
EDIT:
Based on the comments below, if it's safe to assume the directory always has a file in it, and there's nothing else in the directory (e.g., subdirectories), this code can be greatly simplified:
public static File getTextFileInDirectory(String dirPath) {
return new File(dirPath).listFiles()[0];
}
Since you know there will only be one file in the directory, you can get an array of the directory's files and return the first element if it exists, or null if it doesn't.
public static File getFileFromDir(File directory) {
File[] dirFiles = directory.listFiles();
return dirFiles.length > 0 ? dirFiles[0] : null;
}
I am using the following recursive method to list all files and folders within a given directory, however it seems to be listing some files that aren't visible in Windows Explorer - even when I display hidden and system protected files. I have set the method to scan the C:\\ directory, and it hangs after outputting files in the Boot directory and BOOTSECT.BAK. Well, actually, I don't think it hangs - it looks like it returns the final array but there are still more Files and no exceptions are thrown!
private static ArrayList<File> recursiveSearch(File dir){
File[] files = dir.listFiles();
ArrayList<File> result = new ArrayList<File>();
for(File file : files)
if(file.isDirectory()){
result.add(file);
ArrayList<File >tempList = recursiveSearch(file);
for(File temp : tempList)
result.add(temp);
}else{
result.add(file);
System.out.println(file.getPath());
}
return result;
}
I know about FileSystemView but in this occassion I can't use it because I need to apply a custom Filename Filter (which I have excluded from the above, but I have tested and it doesn't affect the methods output). Any help would be appreciated - thanks in advance
This file (bootsect.bak) is detected as a directory, yet returns a null File array. A workaround is to check that it is instantiated:
private static List<File> recursiveSearch(File dir) {
File[] files = dir.listFiles();
List<File> result = new ArrayList<File>();
if (files != null) {
for (File file : files)
if (file.isDirectory()) {
result.add(file);
List<File> tempList = recursiveSearch(file);
for (File temp : tempList)
result.add(temp);
} else {
result.add(file);
System.out.println(file.getPath());
}
}
return result;
}