Reputation: 1179
I need to read all ".txt" files from folder (user needs to select this folder).
Please advise how to do it?
Upvotes: 6
Views: 22297
Reputation: 243
you can use filenamefilter
class it is pretty simple usage
public static void main(String[] args) throws IOException {
File f = new File("c:\\mydirectory");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
}
just create an filenamefilter
instance an override accept method how you want
Upvotes: 12
Reputation: 52185
Assuming you already have the directory, you can do something like this:
File directory= new File("user submits directory");
for (File file : directory.listFiles())
{
if (FileNameUtils.getExtension(file.getName()).equals("txt"))
{
//dom something here.
}
}
The FileNameUtils.getExtension() can be found here.
Edit: What you seem to want to do is to access the file structure from the web browser. According to this previous SO post, what you want to do is not possible due to security reasons.
Upvotes: 2
Reputation: 8530
provide a text box to user to enter the path of directory.
File userDir=new File("userEnteredDir");
File[] allfiles=useDir.listFiles();
Iterate allFiles to filter .txt files using getExtension() method
Upvotes: 1
Reputation: 8101
I wrote the following function that will search for all the text files inside a directory.
public static void parseDir(File dirPath)
{
File files[] = null;
if(dirPath.isDirectory())
{
files = dirPath.listFiles();
for(File dirFiles:files)
{
if(dirFiles.isDirectory())
{
parseDir(dirFiles);
}
else
{
if(dirFiles.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
}
else
{
if(dirPath.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
see if this helps.
Upvotes: 1
Reputation: 1
You need to read the directory and iterate inside it.
it is more a question on Java access to file systems than about MVC
Upvotes: 1