Reading all text files in a directory in Java?

≯℡__Kan透↙ 提交于 2021-02-08 12:16:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!