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.
Related
am trying to compare all the values in my arraylist with all the files in my c:drive
but the code below does not work
List<String> list = new ArrayList<String>();
list.add("*.txt,*.docx");
File file = new File("c:\\*.txt");
if (file.equals(list)) {
System.out.println("file was found");
}else{System.out.println("nothing was found");
}
so the idea is that anytime i run my the code my arraylist would compare itself with my c: drive and list all files that has the extension of "docx and txt" out.
i realised that when i use wildcards it didn't work.
What you need is a FileNameFilter to get all files that pertain to your requirements
Here is an example of getting all *.txt files from current directory. You can implement FileNameFilter to create your own filter that will work on your List.
File f = new File("."); // current directory
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".txt")) {
return true;
} else {
return false;
}
}
};
File[] files = f.listFiles(textFilter);
Hope this helps.
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().
I am trying to iterate over a folder
My files a located in
D:\PROJECT_FOLDER\rootProject\semiRootProject\project\build\resources\main\com\xxxx\pack\file.xlsx
However when I try to iterate over it in console it shows
11:39:06.731 [main] INFO com.xxxx.util.KiePackageCreator - File found: D:\PROJECT_FOLDER\rootProject\semiRootProject\project\build\resources\main\com.
What's the problem? My search loop looks like this.
File fileFolder = new File(projectBuildDir + RESOURCE_SUBFOLDER);
for (File file : fileFolder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
//if (name.endsWith(".xlsx")) {
return true;
//}
//return false;
}
})) {
LOGGER.info("File found: {}.", file.toPath());
if (file.isFile()) {
Resource fileResource = getClassPathResource(file.getName());
String filePath = file.getPath();
String rulePath = MAVEN_RESOURCE_PATH + filePath.substring(filePath.indexOf("com"));
LOGGER.info("Attempt to write into: {}.", rulePath);
kfs.write(rulePath, fileResource);
}
}
List files lists all files and directories in the directory you specify. It does not do so recursively.
Maybe walkFileTree suits you better.
You need to iterate through the sub folders in your code. You are just iterating over the files in the directory that fileFolder is pointing to.
Ok so part of my program searches the C drive for all mp3 files, the only problem is that it won't go into and subfolders. Here is my code so far.
public static List<String> ListFiles() {
List<String> files = new ArrayList<String>();
File folder = new File("C:/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile() && file.toString().contains(".mp3")) {
String fileS = file.getName();
files.add(fileS);
}
}
return files;
}
Try a recursive approach. The path is the current directory that you're in. Recursively call this on each folder and you will get to each file.
public void walk(String path) {
File root = new File(path);
File[] list = root.listFiles();
if (list == null) return;
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath());
}
else {
//do what you want with files
}
}
}
Test whether file is a folder. If it is, pass it to ListFiles and append the return value to files.
For this to work, you need to change ListFiles to accept a File object as argument and start your search with this File instead of with "C:/"
Look into DirectoryStream<Path> class and the Files.isDirectory() method. Basically what you want to do is to check whether each Path is a file or directory.
If it is a directory, you call your method again. Else, you continue iterating.
Globbing is also possible with a directory stream. Saves you a lot of time instead of having to manually check file extensions.
If you wish to continue with your method or with directory stream, you will need to make a few modifications to your program to accomodate recursion.
If you want to do this yourself, you need to make it recursive. Which is what Oswald is getting at. A recursive method is a method that calls itself. So when you search a folder, for each element in it, if its an mp3, add it to the list, if its a folder, call your method again passing that folder in as the input.
I know it's Java question but why not just use Groovy and do it like:
static List<String> listMp3s() {
List<String> files = []
File rootFolder = new File('C:/')
rootFolder.eachFileRecurse(FileType.FILES) {
if (it.name.endsWith('.mp3')) {
files << it.name
}
}
return files
}
I am writing a method to get specific file type such as pdf or txt from folders and subfolders but I am lacking to solve this problem. here is my code
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
My current method list all files but I need specific files
For a filtered list without needing recursion through sub directories you can just do:
directory.listFiles(new FilenameFilter() {
boolean accept(File dir, String name) {
return name.endsWith(".pdf");
}});
For efficiency you could create the FilenameFilter ahead of time rather than for each call.
In this case because you want to scan sub folders too there is no point filtering the files as you still need to check for sub folders. In fact you were very nearly there:
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
if (file.getName().endsWith(".pdf")) {
System.out.println(file.getAbsolutePath());
}
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
if(file.getName().endsWith(".pdf")) {
//it is a .pdf file!
}
/***/
Try using the FilenameFilter interface in you function
http://docs.oracle.com/javase/6/docs/api/java/io/FilenameFilter.html
http://www.mkyong.com/java/how-to-find-files-with-certain-extension-only/ - for a code that has extention filter
Use File.listFiles(FileFilter).
Example:
File[] fList = directory.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.getName().endSwith(".pdf");
}
});
You can use apache fileUtils class
String[] exte= {"xml","properties"};
Collection<File> files = FileUtils.listFiles(new File("d:\\workspace"), exte, true);
for(File file: files){
System.out.println(file.getAbsolutePath());
}
My advice is to use FileUtils or NIO.2.
NIO.2 allows Stream with Depth-First search, for example you can print all files with a specified extension in one line of code:
Path path = Path.get("/folder");
try{
Files.walk(path).filter(n -> n.toString().endsWith(".extension")).forEach(System.out::println)
}catch(IOException e){
//Manage exception
}