8

I followed this question:

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

Scanner s = new Scanner(new File("stuff.txt"));

My question is:

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

Thanks

Community
  • 1
  • 1
alessandrob
  • 1,605
  • 4
  • 20
  • 23

4 Answers4

16

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 that if you have any files that you don't want to include, you can give listFiles() a FileFilter argument to filter them out.

arshajii
  • 127,459
  • 24
  • 238
  • 287
8

Yes, create your file object by pointing it to a directory and then list the files of 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
}
nullByteMe
  • 6,141
  • 13
  • 62
  • 99
3

You can try this in 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 
  }
 }
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1
    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
                }
            }
        }
    }
Jayesh
  • 6,047
  • 13
  • 49
  • 81
  • I'm no expert, but I think your `if(listOfFiles!=null)` is unnecessary. You just created the `listOfFiles` so how can it be null? – nullByteMe Jul 18 '13 at 16:55
  • Ughh.. same with your `if(file!=null)`... you're testing whether an object reference exist which you just made prior to the test! – nullByteMe Jul 18 '13 at 17:02
  • Null check on `lisOfFiles` is okay (it could happen if the path exists but is a file) but on the `file` isn't required. +1 for the `isFile()` check anyway. – Ravi K Thapliyal Jul 18 '13 at 17:07
  • @RaviThapliyal good call, I didn't think about that with `listOfFiles` because I would have written my code to first check if `file` is a directory and then processed `listFiles()`. – nullByteMe Jul 18 '13 at 17:11