Let's say, I have a folder called maps
and inside maps
I have map1.txt
, map2.txt,
and map3.txt
. How can I use Java and the BufferReader
to read all of the .txt
files in folder maps
(if it is at all possible)?
Asked
Active
Viewed 7.6k times
20

Bilesh Ganguly
- 3,792
- 3
- 36
- 58

test
- 17,706
- 64
- 171
- 244
-
Possible duplicate of [Read all files in a folder](http://stackoverflow.com/questions/1844688/read-all-files-in-a-folder) – jsingh Jan 16 '17 at 17:30
7 Answers
48
Something like the following should get you going, note that I use apache commons FileUtils instead of messing with buffers and streams for simplicity...
File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
String content = FileUtils.readFileToString(file);
/* do somthing with content */
}
}

Community
- 1
- 1

Andrew White
- 52,720
- 19
- 113
- 137
-
Ah. Thanks... but a note: would it make it easier to manage if all of the files were named mapNUMBER.txt? As in map3.txt, map4.txt, etc. – test May 07 '11 at 22:17
-
This code won't work as is because there's no declaration of the variable 'file' used on line 6. Not sure why you would write it up this way, maybe it's supposed to be more pseudocode style, but file should be replaced with listOfFiles[i], or the file variable should be declared if it's going to be used. – paul Jan 31 '13 at 16:47
-
4Just for the record, `for(File file : folder.listFiles())` is quite a bit shorter and nicer. :) – Dolda2000 Jan 31 '13 at 17:38
-
@Dolda2000 agreed, I am not real sure why I answered this way. Perhaps I pulled an existing example. – Andrew White Jan 31 '13 at 21:00
22
I would take @Andrew White answer (+1 BTW) one step further, and suggest you would use FileNameFilter to list only relevant files:
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
String content = FileUtils.readFileToString(file);
// do something with the file
}
-
@Shahryar it's not a redundant answer, it's a different and valid answer. – Kenny Cason Jun 05 '13 at 18:46
-
1@KennyCason As I see it's just like previous answer! What is the advantage of using FileNameFilter? – Shahryar Jun 07 '13 at 19:15
-
@Shahryar yes, which is imo an equal, and possibly, a cleaner example. It's also good to know the existence of `other` solutions. You'll see on SO that there are many similar, but different solutions to a problem are supplied. – Kenny Cason Jun 08 '13 at 04:06
-
@KennyCason "It's also good to know the existence of other solutions" good word :-) – Shahryar Jun 08 '13 at 10:59
5
final File folder = new File("C:/Dev Tools/apache-tomcat-6.0.37/webapps/ROOT/somefile");
for (final File fileEntry : folder.listFiles()) {
System.out.println("FileEntry Directory "+fileEntry);

Lokesh
- 313
- 2
- 12
-
1Does this add any improvement over the other answers? Or is the for-each just a syntax preference? – Patrick M Sep 30 '14 at 18:14
-
1
1
With NIO
you can do the following:
Files.walk(Paths.get("/path/to/files"))
.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".txt"))
.map(FileUtils::readFileToString)
// do something
To read the file contents you may use Files#readString
but, as usual, you need to handle IOException
inside lambda expression.

xuesheng
- 3,396
- 2
- 29
- 38
0
I think it's good way to read all .txt files from maps and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}

Mohammad
- 81
- 4
0
If you want a better way of doing this using the new java.nio api, then this is the way, taken from the java docs
Path dir = ...;
try (DirectoryStream<Path> stream =
Files.newDirectoryStream(dir, "*.txt")) {
for (Path entry: stream) {
System.out.println(entry.getFileName());
}
} catch (IOException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can // only be thrown by newDirectoryStream.
System.err.println(x);
}

Shervin Asgari
- 23,901
- 30
- 103
- 143
0
Using only JDK, If all your files are in one directory:
File dir = new File("path/to/files/");
for (File file : dir.listFiles()) {
Scanner s = new Scanner(file);
// do something with file
s.close();
}
To exclude files, you can use listFiles(FileFilter)

Duy Đặng
- 409
- 1
- 7
- 15