February 03, 2012

How to find out given directory file names and inside content:

Purpose of Each Program:
MapExample: Here key is filename and values is inside content.
OnlyExt: Here Dynamically decides type of file.

class OnlyExt implements FilenameFilter {
String ext;
public OnlyExt(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}
public class MapExample {
public static void main(String[] args) throws Exception {
FilenameFilter ff = new OnlyExt("txt");
File folder = new File("C://Myjavacafe//MapExample");
File[] files = folder.listFiles(ff);
Map<String, String> map = new LinkedHashMap<String, String>();
for (int i = 0; i < files.length; i++) {
FileReader fr = new FileReader(files[i].getPath());
BufferedReader reader = new BufferedReader(fr);
String st = "", str = " ";
while ((st = reader.readLine()) != null) {
str += st;
}
map.put(files[i].getName(), str);
}
Set set = map.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.println(me.getKey() + " \t:\t " +
me.getValue());
}
}
}

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts