Java Read the many txt files in the folder and process them.

I followed this question :

Now in my case I have 720 files named this way: "dom 24 mar 2013_00.50.35_128.txt", each file has a different date and time. In the testing phase, I used Scanner with a specific txt file to perform some operations on it:

Scanner s = new scanner (new file ("stuff.txt"));

My question is:

How can I reuse the scanner and read all 720 files without having to set the exact name on the scanner?

thanks

+7
java
source share
4 answers

Assuming you have all the files in one place:

File dir = new File("path/to/files/"); for (File file : dir.listFiles()) { Scanner s = new Scanner(file); ... s.close(); } 

Note: if you have files that you do not want to include, you can give listFiles() a FileFilter argument to filter them.

+14
source share

Yes, create your file object by pointing it to a directory, and then list the files in that directory.

 File dir = new File("Dir/ToYour/Files"); if(dir.isDir()) { for(File file : dir.listFiles()) { if(file.isFile()) { //do stuff on a file } } } else { //do stuff on a file } 
+6
source share

You can try it this way

  File folder = new File("D:\\DestFile"); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.isFile()&&(file.getName().substring(file.getName().lastIndexOf('.')+1).equals("txt"))) { // Scanner } } 
+3
source share
  File file = new File(folderNameFromWhereToRead); if(file!=null && file.exists()){ File[] listOfFiles = file.listFiles(); if(listOfFiles!=null){ for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { // DO work } } } } 
+1
source share

All Articles