Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading through Files in a Directory

 
Ron Rea
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I need to read through several text files, all located within the same directory. I need to loop through each line of the text file, parse the line out, perform some processing, then read the next line. When I get to the last line, I want to read the next file in the directory, if another file exists.
Does anyone know of a way to read through each file within a directory? ie. All lines in file1, then all lines in file2, then al lines in file3. I know how to read through the text lines, but I do not know how to read the next file in the directory. The files names may not be known in advance, but I still need to read the next file available.
ex. File1.txt
- Data line 1
- Data line 2
- Data line 3
File2.txt
- Data line 1
- Data line 2
File7.txt
- Data line 1
- Data line 2
- Data line 3
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The File class has a list() method to list the files in a directory, returning them in a
String[] array. Just loop through the array to read each file in turn.
 
Paul Michael
Ranch Hand
Posts: 697
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or you can also use the listFiles() method which returns an array of File Objects... and recurse through those Objects.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!