Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 483
alessandrob Avatar asked Jul 18 '13 16:07

alessandrob


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

like image 179
arshajii Avatar answered Oct 01 '22 10:10

arshajii


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
}
like image 31
hax0r_n_code Avatar answered Oct 01 '22 09:10

hax0r_n_code