问题
How would I scan an entire folder in my Java code and then read each text file in to a separate array? What I'm trying to do is have a set of LocationNodes(class I created) on a map app that I'm creating for my college campus/side project for my resume.
When the code initializes, I want my app to scan for all text files in my "LocationTextFiles" folder. Each text file has 3 sets of text: Line 0 (the name of the location), Line 1 (Hours the building is open), and Line 2-EOF (description of the location). I then would take these lines stick them in a new LocationNode object every time and then create a new LocationNode object to repeat the process until all files that were found have been read.
What's the best way to go about doing this? I have the class set up with it's attributes (name, hoursText, and descriptionText), so I'm assuming this function that I would create would need to be a public method of this same LocationNode class?
回答1:
Here you go,
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 */
}
}
You can use array instead of content
. But I would suggest don't do it, if you have huge number of files or each file is huge. When I huge, I mean the size exceed RAM size.
来源:https://stackoverflow.com/questions/29939379/reading-all-text-files-in-a-directory-in-java