How to get all text files from one folder using Java?

I need to read all the ".txt" files from a folder (the user needs to select this folder).

Please advise how to do this?

+6
source share
5 answers

you can use the filenamefilter class, this is a fairly simple use of public static void main (String [] args) throws an 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 instance of filenamefilter for the override accept method as you want

+10
source

Assuming you already have a 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 file NameNameUtils.getExtension () can be found here .

Edit: what you want to do is access the file structure from a web browser. According to this previous SO-mail, what you want to do is not possible due to security concerns.

+2
source

You need to read the directory and repeat it inside.

more a question about Java access to file systems than about MVC

+1
source

I wrote the following function, which will search for all 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 that helps.

+1
source

Provide a text box to the user to enter the directory path.

 File userDir=new File("userEnteredDir"); File[] allfiles=useDir.listFiles(); 

Iterate allFiles to filter .txt files using getExtension () method

+1
source

Source: https://habr.com/ru/post/906371/


All Articles