读取Java目录中的所有文本文件? [英] Reading all text files in a directory in Java?

查看:90
本文介绍了读取Java目录中的所有文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何扫描Java代码中的整个文件夹,然后将每个文本文件读入单独的数组中?我想做的是在地图应用程序上有一组LocationNodes(我创建的类),该应用程序是我为大学校园/边际项目创建的,用于我的履历表.

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.

代码初始化时,我希望我的应用扫描"LocationTextFiles"文件夹中的所有文本文件.每个文本文件具有3组文本:第0行(位置名称),第1行(建筑物开放时间)和第2-EOF行(位置说明).然后,我将这些行每次都将其粘贴到新的LocationNode对象中,然后创建一个新的LocationNode对象以重复该过程,直到读取找到的所有文件为止.

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.

执行此操作的最佳方法是什么?我已经用它的属性(名称,hoursText和descriptionText)设置了类,所以我假设要创建的此函数将需要是同一LocationNode类的公共方法?

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?

推荐答案

来了,

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 */
  } 
}

您可以使用数组代替 content .但是我建议不要这样做,如果您有大量文件或每个文件都很大.当我很大时,我的意思是大小超过了RAM大小.

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.

这篇关于读取Java目录中的所有文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆