Reputation: 31
Could someone give me an example of how you could read in a directory of text files and read each text file line by line using Java?
So far I have:
String files;
File folder = new File(file_path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
// do something here??
}
}
Upvotes: 0
Views: 29866
Reputation: 48599
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;
public class MyProg {
public static void main(String[] args) throws IOException {
String target_dir = "./test_dir";
File dir = new File(target_dir);
File[] files = dir.listFiles();
for (File f : files) {
if(f.isFile()) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(
new FileReader(f));
String line;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
}
}
Upvotes: 6
Reputation: 13123
In the Java javadocs, look up FileReader, then BufferedReader -- the first reads a file, the second takes a reader as a constructor parameter and has a readline() method.
I agree this is a poor question, but file I/O is difficult to discern without some guidance, and the tutorials often spend too much time with things that you don't need for this purpose. You should still go through the tutorial, but this will get you started for this purpose.
Upvotes: 1