cancel
Showing results for 
Search instead for 
Did you mean: 

How to search a file and get its content from a Folder

Former Member
0 Kudos

Hi,

I have a folder which has some 100 files, now i need to search a particular file from these folder and get its content.

Can any one please suggest me how to do this?

Thanks & Regards,

Laxmi

Accepted Solutions (0)

Answers (5)

Answers (5)

Former Member
0 Kudos

hi,

use BufferedStreams for performance issue.

Regards,.

Srikanth Reddy.T

Edited by: Srikanth Thatipally on Jan 6, 2009 11:06 AM

Former Member
0 Kudos

Hi,

U can find a particular file using this code

import java.io.*;

public class FileExt

{

public static void main(String args[])

{

try

{

String[] filesList;

File dir = new File(".");

filesList= dir.list(new FileFilter());

for (int i=0;i {

System.out.println(filesList<i>);

}

}

catch(Exception e){}

}

}

class FileFilter implements FilenameFilter

{

public boolean accept(File dir, String name)

{

return (name.endsWith(".java"));

}

}

Once u get the file u can use FileOutputStream or BufferedOutputStream to read the contents.

Regards,

Srikanth Reddy.T

Edited by: Srikanth Thatipally on Jan 6, 2009 11:04 AM

Former Member
0 Kudos

hi!

you can use this code to get the name of all the file in a folder and then you can search the required file , for which you can use a class called FilenameFilter.

File folder = new File("c:/");

File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {

if (listOfFiles<i>.isFile()) {

//your code to search the file

} else if (listOfFiles<i>.isDirectory()) {

//your code

}

}

regards

vishal

Former Member
0 Kudos

Hi Lakshmi,

For implementing the above code you need to use commons-io-1.2.3.jar file

and then import import org.apache.commons.io.FileUtils;

It will work fine

Regards

Narendra

Former Member
0 Kudos

Hi Laxmi,

You can use the below mentioned code to search a perticular file from a folder.

int i=0;

File root = new File("C:/Xlf");// Specify the folder path

File file = null;

String[] extensions = { "xlf" };//Specify the type of file you want to search like txt, zip etc.

boolean recursive = true;

//

// Finds files within a root directory and optionally its

// subdirectories which match an array of extensions. When the

// extensions is null all files will be returned.

//

// This method will returns matched file as java.io.File

//

Collection files = FileUtils.listFiles(root, extensions, recursive);

ArrayList arrayList = new ArrayList();

for (Iterator iterator = files.iterator(); iterator.hasNext();) {

String fileName = "file";

i++;

fileName = fileName +i;

arrayList.add(fileName);

file = (File) iterator.next();

System.out.println("File are = " + file.getAbsolutePath());

}

please revert if you require more info

regards

Narendra