Finding files that don't have a wildcard - java

So I have csvs:
R-15_A.csv
R-16_A.csv
R-17_A.csv
R-15_B.csv
R-15_A_Processed.csv
R-15_B_Processed.csv
R-16_A_Processed.csv
R-17_A_Processed.csv
Been using commons.io's wildcardfilefilter but am confused at the filter.
So if I wanted to get a list of files that are A but not processed what would I use for the filter?
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("filter?");
File[] files = dir.listFiles(fileFilter);
for(File f:files)
{
log.info("service2: "+f.getName());
}
log.info("service2: size "+files.length);

"*A.csv" should match 'A' but not 'Processed'

Related

How to access the folder name from the directory

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.

find specific file type from folder and its sub folder

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
}

Filtering File objects in java to populate a jComboBox

Using the code below populates my JComboBox with the complete path. is there an easy way to filter it to only show the file name itself in the JComboBox.
String path = "\\\\intdatserver1\\NY_files";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
final JComboBox jList1 = new JComboBox(listOfFiles);
I think you could figure it out by yourself but if you insist...
List<String> fileNames = new ArrayList<String>();
for (File file : listOfFiles) {
if (file.isFile()) {
fileNames.add(file.getName());
} else if (file.isDirectory()) {
// handle directory
}
}
You can create a new String array or List<String> wiht the file names only, using the getName() method from the File class.

Java listFiles displaying Boot directory and other 'protected' Files

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;
}

Scan a file folder in android for file paths

So i have a folder at "mnt/sdcard/folder" and its filled with image files. I want to be able to scan the folder and for each of the files that is in the folder put each file path in an arraylist. Is there an easy way to do this?
You could use
List<String> paths = new ArrayList<String>();
File directory = new File("/mnt/sdcard/folder");
File[] files = directory.listFiles();
for (int i = 0; i < files.length; ++i) {
paths.add(files[i].getAbsolutePath());
}
See listFiles() variants in File (one empty, one FileFilter and one FilenameFilter).
Yes, you can use the java.io.File API with FileFilter.
File dir = new File(path);
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File file) {
return file.getAbsolutePath().matches(".*\\.png");
}
};
File[] images = dir.listFiles(filter);
I was quite surprised when I saw this technique, as it's quite easy to use and makes for readable code.

Categories