简体   繁体   English

使用BufferedReader读取多个文件

[英]Reading multiple files using BufferedReader

I want to read texts from two or more files using a single BufferedReader object. 我想使用一个BufferedReader对象从两个或更多文件中读取文本。

This is how I did it in my code. 这就是我在代码中做到的方式。

Charset charset = Charset.forName("UTF-8");
Path p1 = Paths.get("sum1.csv");

List<String> list = new ArrayList<String>();
BufferedReader reader = Files.newBufferedReader(p1, charset);
try {
    String line;
    while((line = reader.readLine()) != null && !line.isEmpty()){
        list.add(line);
    }
} catch (IOException e) {
    System.err.format("IOException: %s%n", e);
    reader.close();
}

Path p2 = Paths.get("sum2.csv");
reader = Files.newBufferedReader(p2, charset);
try {
    String line;
    while((line = reader.readLine()) != null && !line.isEmpty()){
        list.add(line);
    }
} catch (IOException e) {
    System.err.format("IOException: %s%n", e);
    reader.close();
}

The code compiled and run correctly. 该代码已编译并正确运行。

What is the standard way to deal with this problem? 解决此问题的标准方法是什么? Is it possible to read two or more files using a single BufferedReader? 是否可以使用单个BufferedReader读取两个或更多文件?

Charset charset = Charset.forName("UTF-8");
List<String> list = new ArrayList<String>();
try(
  FileInputStream is1=new FileInputStream("sum1.csv");
  FileInputStream is2=new FileInputStream("sum2.csv");
  SequenceInputStream is=new SequenceInputStream(is1, is2);
  BufferedReader reader=new BufferedReader(new InputStreamReader(is, charset));)
{
  try {
      String line;
      while((line = reader.readLine()) != null && !line.isEmpty()){
          list.add(line);
      }
  } catch (IOException e) {
      System.err.format("IOException: %s%n", e);
  }
}

By the way, did you mean 顺便说一句,你的意思是

String line;
while((line = reader.readLine()) != null)
  if(!line.isEmpty()) list.add(line);

for your inner loop? 为你的内循环? Your code stops at the first empty line, my suggested alternative skips empty lines. 您的代码在第一个空行处停止,我建议的替代方法将跳过空行。 But I can only guess your real intention. 但是我只能猜测你的真实意图。

In the code above, you did create a new BufferedReader to read from the second file. 在上面的代码中,您确实创建了一个新的BufferedReader以从第二个文件读取。 What you've done is perfectly fine, although it would make sense to put the repeated code into a method that takes the filename and the list of strings as arguments. 尽管将重复的代码放入以文件名和字符串列表作为参数的方法中,这是很有意义的,但是您所做的一切都很好。

You've got one little glitch - if there's an empty line in the middle of either of your files, your program stops reading when it gets to it. 您会有一个小故障-如果两个文件中间都有一个空行,则程序在到达文件时将停止读取。 I'm not sure if that's actually what you want. 我不确定这是否真的是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM