I am working in a desktop application for windows using Java. In my application, there is a requirement to search all .php. To do this,
here I use recursive methods.
import java.io.File;
public class Copier {
public static void find(String source,String rep) {
File src = new File(rep);
if (src!= null && src.exists() && src.isDirectory()) {
String[] tab = src.list();
if (tab != null) {
for(String s : tab) {
File srcc = new File(rep+"\\"+s);
if (srcc.isFile()) {
if (srcc.getName().matches(".*"+source+"$")) {
System.out.println(s);
}
} else {
find(source,srcc.getAbsolutePath());
}
}
} else {
//System.out.println(" list is null");
}
}
}
and here i use iterative algorithm with breadth-first-search with queue but it not work
import java.io.File;
import java.util.LinkedList;
public class Copier {
public static void find(String source,String rep)
{
File src=new File(rep);
LinkedList<File> qu=new LinkedList();
if(src!=null && src.exists() && src.isDirectory())
{
File[] tab=src.listFiles();
if(tab!=null)
{
for(File s:tab)
{
qu.addLast(s);
}
while(!qu.isEmpty())
{
File srcc=qu.getFirst();
qu.removeFirst();
if(srcc.isFile())
{
if(srcc.getName().matches(".*"+source+"$"))
System.out.println(srcc.getName());
}
else
{
System.out.println(srcc.getName());
qu.addLast(srcc);
}
}
}
}
}
public static void main(String[] args)
{
try {
find(".php","C:\\AppServ");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Anouar,
try to use Apache Commons IO.
You can use class
described here in API Javadoc.
It provides very useful, performance-optimized and bug-free static methods to search files (listFiles and iterateFiles methods), copy/move files and directories, reading files to String in “one-line-of-code” and many more nice stuff.
There is no need to reinvent the wheel 😉