alessandrob
alessandrob

Reputation: 1615

Java - Read many txt files on a folder and process them

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

Upvotes: 8

Views: 42683

Answers (4)

nullByteMe
nullByteMe

Reputation: 6391

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
}

Upvotes: 8

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

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 
  }
 }

Upvotes: 3

arshajii
arshajii

Reputation: 129577

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.

Upvotes: 16

Jayesh
Jayesh

Reputation: 6111

    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
                }
            }
        }
    }

Upvotes: 1

Related Questions