twitter
    Find out what I'm doing, Follow Me :)

Text File සර්ච් කිරිම

sub folder එකක් ඇතුලේ text file පමනක් සොයගැනීමට ක්‍රම කිහිපයක් ඇත.
මේ සදහා file list හො file filter එකක් යොදාගත හැක.
file filter එකක් යොද ගනීනම් මුලින් filter එක අපට අවෂ්‍ය පරිදි එම interface එකේ attributes සාද ගත යුතුය. පහත පරිදි එය සකසා ගත හැක.

protected fileFilter()
{
txtFilter = new FileFilter() //filefilter atribute වෙනස් කිරීම
{
public boolean accept(File file)
{
String sPath = file.getName();//file වල නම් ලබා ගැනීම

if( sPath.endsWith(".txt") )
{
return true;
}
else
{
return false;
}
}
};

}

ඉහත interface එක වෙනත් ෆයිල් වර්ග සොයගැනීමට ද යොද ගත හැක. ".txt" යන ස්ථානයෙහි ඔබට අවෂ්‍ය extention (උදා- ".jpg" , ".avi") එක ලබා දීමෙන් එය කරගැනීමට පුලුවන්.

මෙමගින් අපි text file සොයගත්තද එය එක් ෆොල්ඩරයක් සදහා පමණි. දැන් එය sub folder වලත් සර්ච් කල හැකි ලෙස සාදන්නේ කෙසේදැයි බලමු. මෙ සදහා recurtion method එකක් භාවිතා කිරීම වැඩය පහසු කරවයි. recurtion method

එකක් යනු method එකක් මගින් එම method එකම නැවත නැවත call කිරීමයි.

එම method එක වැඩ කරන විටම සොයගත් text ෆයිල් වෙනස් නොවන List එකකට දම ගතයුතුය. අවසානයේ text ෆයිල් list එක පහසුවෙන් ලැබේ. අදාල code එක පහත පරිදි වේ.

protected void getFiles(String dirPath) throws IOException
{
File dir = new File(dirPath);
if(dir.exists()) // සියලු file තෝරා ගැනීම හා list කිරීම
{
File[] allFiles = dir.listFiles();
if(allFiles != null)
{

for(int n = 0; n < allFiles.length; n++)
{
if(allFiles[n].isDirectory())
{
String ss=allFiles[n].getPath();

this.getFiles(ss);
}
}
}
else
{
System.out.println("No files in folder: "+ dirPath);
}

File[] txtFiles = dir.listFiles(txtFilter); // සියලු text file තෝරා ගැනීම හා list කිරීම
if(txtFiles != null)
{
for(int n = 0; n < txtFiles.length; n++)
{
String path=txtFiles[n].getCanonicalPath(); //absolute path එක ලබා ගැනීම
r.read(path); //read කරන්න ‍යැවීම
}
}
else
{
System.out.println("No text files in folder: "+ dirPath);
}

}
else
{
System.out.println("Folder "+ dirPath + " does not exist!");
}
}

1 comments:

Thilanka Kaushalya said...

එලකිරි දිලුම්. ඔහොම යං......

Post a Comment