String & Date Utils




How to get files from folder with matching File Name
There will a requirement which should get the list of files from a folder or from the directory files name start with the some regular expression i.e . text.txt , test.txt  .. Here regular expression can be "te".


In this scenario we should use the below given code




package com;


import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


public class SearchFilesInFolder {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
File file = new File("D:/test");
String regExp = "te";
List list = new ArrayList();
if(file.isDirectory()){
String files[] = file.list();
System.out.println(Arrays.toString(files));
for(int i=0;i<files.length;i++){
if(files[i].toLowerCase().startsWith(regExp.toLowerCase())){
list.add(files[i]);
}
}

}
Iterator itr = list.iterator();
System.out.println("List of files which starts with te");
while(itr.hasNext()){
String fileName = (String)itr.next();
System.out.println(fileName);
}

}catch(Exception e){
e.printStackTrace();
}
}


}






D:/test folder has six files which also does not start with "te". So, after executing the program we will get only four files since we have applied filter..


outcome
-----------
[another file.txt, someotherfile.txt, test.txt, teste.txt, testing.txt, text.txt]
List of files which starts with te
test.txt
teste.txt
testing.txt
text.txt



Reading Directory and Sub Directories from the given path


import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DirectoryReader {

static int spc_count=-1;
List machedFileList = new ArrayList();
List process(File aFile,String pattern) {

spc_count++;
String spcs = "";
for (int i = 0; i < spc_count; i++)
spcs += " ";
if(aFile.isFile() && aFile.getName().toLowerCase().matches(pattern.toLowerCase())){
System.out.println(spcs + "[FILE] " + aFile.getName());
machedFileList.add(aFile.getName());
}
else if (aFile.isDirectory()) {
System.out.println(spcs + "[DIR] " + aFile.getName());
File[] listOfFiles = aFile.listFiles();
if(listOfFiles!=null) {
for (int i = 0; i < listOfFiles.length; i++)
process(listOfFiles[i],pattern);
} else {
System.out.println(spcs + " [ACCESS DENIED]");
}
}
spc_count--;
return machedFileList;

}

public static void main(String[] args) {
String nam = "C:/Documents and Settings/bgh26443/My Documents/Downloads";
String sa="wsr"+".+";
File aFile = new File(nam);
DirectoryReader reader = new DirectoryReader();
List machedFileList = reader.process(aFile,sa);
System.out.println(machedFileList.toString());
}

}