Friday, September 11, 2015

Java file folder operation



//Apache Common IO
//Finding list of files as per file extension . Recusrsive files and directories

package FileSystem;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.io.FileUtils;

public class FileFilterApacheCommonIO {

public static void main(String[] args) {

FileFilter F = new FileFilter();
F.filter();

}

}

class FileFilter {
public void filter() {
String path = "C:/Test";
File f = new File(path);
String fileExtensions[] = {"txt","java"};
Collection<File> filterList = FileUtils.listFiles(f, fileExtensions,
true);
Iterator<File> fListIterator = filterList.iterator();
while (fListIterator.hasNext()) {
System.out.println(fListIterator.next().getAbsoluteFile());
}

}

}

//********************************************************************************
// List of all files and folders. Recusrsive files and directories

package FileSystem;

import java.io.File;

public class RecursiveFileDirectory {

public static void main(String[] args) {
// TODO Auto-generated method stub
Recursive R = new Recursive();
R.readRecursive("C:/Test");
}
}
class Recursive {
String path;
public void readRecursive(String path) {
File f = new File(path);
File[] fileList = f.listFiles();
if (fileList == null)
return;
// check the fileList
for (int i = 0; i < fileList.length; i++) {
/*if fileList objec is directory
recurse through directories until the fileList
object returns null*/
if (fileList[i].isDirectory()) {
readRecursive(fileList[i].getAbsolutePath());
System.out.println(fileList[i].getAbsoluteFile().getPath());
}

else if (fileList[i].isFile()) {
System.out.println(fileList[i].getAbsoluteFile().getPath());
}
}
}
}

//********************************************************************************
// find files in directories and subdirectories based on file name/ folder name using filter

package FileSystem;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;

public class FileList {

public static void main(String[] args) {
// TODO Auto-generated method stub
new FindFileName().filter();

}

}

class FindFileName {
public void filter() {
File f = new File("C:/Test");
String fName = "Helloworld";
String fileName = fName.toLowerCase();
IOFileFilter fileFilter = FileFilterUtils.nameFileFilter(fileName);
Collection<File> listOfFiles = FileUtils.listFiles(f, fileFilter, null);

Iterator<File> fileIterator = listOfFiles.iterator();
while (fileIterator.hasNext()) {
System.out.println(fileIterator.next().getName());

}
}
}



No comments:

Post a Comment