读取文件夹中的整个文件
Java中有没有一种方法可以让我在java中指定一个目录,然后它一个接一个地读取整个文件?
否则有没有办法在java中读取正则表达式文件?因此,如果文件夹中的所有文件都以 gh001_12312 gh002_12312、gh003_12911、gh004_22222、gh005_xxxxx 等开头
Is there a way in Java where I can specify a directory in java and it reads the whole file one by one?
Otherwise is there a way to do a regex file read in java? So if all the files in the folder all starts with gh001_12312 gh002_12312, gh003_12911, gh004_22222, gh005_xxxxx, etc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
标准 Java 库提供了一种通过 File#listFiles。
基本上:
此外,还有一个重载方法允许指定过滤器,该过滤器可用于修剪列表中返回的元素。
如果您还想根据文件名进行一些过滤,请查看 字符串,模式和匹配器。如果您知道只有文件或文件将遵循特定的命名约定,那么还有一个 File.listFiles(FilenameFilter) 选项,它仅提供表示文件名的字符串。
The standard Java library provides a way of obtaining an array of
File
elements which are in a directory via File#listFiles.Basically:
Furthermore, there is an overloaded method that allows a filter to be specified which can be used to prune the elements returned in the list.
If you want to do some filtering based on file name as well then have a look at String, Pattern, and Matcher. If you know there will be only files or files will follow a certain naming convention there is also a
File.listFiles(FilenameFilter)
options which provides only a String representing the file name.您可以结合使用 commons-io 中的以下方法。第一种方法使您可以选择递归地迭代目录中与特定扩展名匹配的所有文件(还有另一种重载方法允许您提供自己的过滤器)。第二种方法将文件的全部内容作为 String 对象读取。
You can use the combination of below methods from commons-io. The first method gives you option of iterating through all the files in a directory, recursively, that match a particular extension (there is another overloaded method that allows you to provide your own filter). The second method reads the entire contents of the file as a String object.
我在这里重用@Tim Bender 的代码:
首先获取@Tim Bender 所示的所有所需文件的列表(为了完整性再次在此处显示)。并且不需要第三方库。
现在迭代这个数组并使用 java.nio API 一次性读取文件(不使用 br.readLine())
希望有帮助
I am reusing the the code from @Tim Bender here:
First get a list of all the needed files as shown by @Tim Bender (shown here again for completeness). And no third party libraries are needed.
Now iterate over this array and use
java.nio
API for file reading in a single go (withoutbr.readLine()
)Hope this help