Java - 多个输入文件 [英] Java - multiple input files

查看:119
本文介绍了Java - 多个输入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用Java读取多个输入文件?我需要读取多个输入(几个文本文档)并创建一个术语文档矩阵。

我可以读取这样一个文件:

How does one read multiple input files in Java? I need to read multiple inputs (several text documents) and create a Term Document Matrix.
I can read one file like this:

  File file = new File("a.txt"); 
  int ch;
  StringBuffer strContent = new StringBuffer("");
  FileInputStream stream = null;  
  try
   {
     stream = new FileInputStream(file);   
     while( (ch = stream.read()) != -1)
        strContent.append((char)ch); 
      stream.close();   
   }

是否有任何库可以读取多个输入文件?或者我只需要循环读取所有文件?所有文件都是 txt。

Is there any library to read multiple input files? Or I just need to loop and read all files? All files are txt.

推荐答案


有没有库可以读取多个输入文件?

Is there any library to read multiple input files?

AFAIK,没有。

这是你的代码适合阅读多个文件到 strContent 缓冲区。

Here is your code adapted to read multiple files into the strContent buffer.

  String names = new String[]{"a.txt", "b.txt", "c.txt"};
  StringBuffer strContent = new StringBuffer("");

  for (String name : names) {
      File file = new File(name); 
      int ch;
      FileInputStream stream = null;  
      try {
          stream = new FileInputStream(file);   
          while( (ch = stream.read()) != -1) {
              strContent.append((char) ch); 
          }
      } finally {
          stream.close();  
      } 
   }

请注意,我已经移动了关闭调用 finally 块,以便在读取流时出现问题时不会泄漏文件描述符。主要的变化是简单地将代码放入循环中,并调整几个语句的顺序。

Note that I've moved the close call into a finally block so that you don't leak file descriptors if there is a problem reading the stream. The main changes are to simply put your code into a loop, and tweak the order of a couple of the statements.

这篇关于Java - 多个输入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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