【问题标题】:BufferedReader: read multiple lines into a single stringBufferedReader:将多行读入单个字符串
【发布时间】:2011-07-27 19:48:30
【问题描述】:

我正在使用 BufferedReader 从 txt 文件中读取数字进行分析。我现在要解决的方法是 - 使用 .readline 读取一行,使用 .split 将此字符串拆分为字符串数组

public InputFile () {
    fileIn = null;

    //stuff here

    fileIn = new FileReader((filename + ".txt"));
    buffIn = new BufferedReader(fileIn);


    return;
    //stuff here
}

public String ReadBigStringIn() {
    String line = null;

    try { line = buffIn.readLine(); }
    catch(IOException e){};

    return line;
}

public ProcessMain() {
    initComponents();
    String[] stringArray;
    String line;

    try {
        InputFile stringIn = new InputFile();
        line = stringIn.ReadBigStringIn();
        stringArray = line.split("[^0-9.+Ee-]+"); 
        // analysis etc.
    }
}

这很好用,但是如果 txt 文件有多行文本怎么办?有没有办法输出一个长字符串,或者可能是另一种方法?也许使用while(buffIn.readline != null) {}?不知道如何实现。

赞赏的想法, 谢谢。

【问题讨论】:

    标签: java text-processing bufferedreader


    【解决方案1】:

    如果你只是想将整个文件读入一个字符串,我建议你使用GuavaFiles类:

    String text = Files.toString("filename.txt", Charsets.UTF_8);
    

    当然,这是假设您想要维护换行符。如果你想删除换行符,你可以以这种方式加载它,然后使用 String.replace,或者你可以再次使用 Guava:

    List<String> lines = Files.readLines(new File("filename.txt"), Charsets.UTF_8);
    String joined = Joiner.on("").join(lines);
    

    【讨论】:

      【解决方案2】:

      听起来你想要 Apache IO FileUtils

      String text = FileUtils.readStringFromFile(new File(filename + ".txt"));
      String[] stringArray = text.split("[^0-9.+Ee-]+");
      

      【讨论】:

        【解决方案3】:

        如果您创建一个StringBuilder,那么您可以将每一行附加到它,并在末尾使用toString() 返回字符串。

        您可以将 ReadBigStringIn() 替换为

        public String ReadBigStringIn() {
                StringBuilder b = new StringBuilder();
        
                try {
                    String line = buffIn.readLine();
                    while (line != null) {
                        b.append(line);
                        line = buffIn.readLine();
                    }
                }
                catch(IOException e){};
        
                return b.toString();
        }
        

        【讨论】:

          【解决方案4】:

          你是对的,这里需要一个循环。

          通常的习惯用法(仅使用纯 Java)是这样的:

          public String ReadBigStringIn(BufferedReader buffIn) throws IOException {
              StringBuilder everything = new StringBuilder();
              String line;
              while( (line = buffIn.readLine()) != null) {
                 everything.append(line);
              }
              return everything.toString();
          }
          

          这将删除换行符 - 如果您想保留它们,请不要使用 readLine() 方法,而只需读入 char[](并将其附加到您的 StringBuilder)。

          请注意,这个循环会一直运行到流结束(如果它没有结束则会阻塞),所以如果你需要一个不同的条件来完成循环,就在那里实现它。

          【讨论】:

          • 不好的是你不能在服务器上使用它,因为它们无休止地等待 readLine()
          • @Niton 服务器如何无休止地等待?如果 readLine 尝试从没有结束的开放流中读取,它将无休止地等待,但这并不特定于服务器。
          • 是的,但是服务器流(套接字流)只有在它们关闭时才会结束,因此在服务器上最好使用“消息结束条件”。 (例如 HTTP 请求末尾的空行保持流打开但告诉客户端请求已完成)
          • 您的回答是正确的,但遗憾的是对我来说不适用于服务器/协议。但是我有一个解决方案,只是想指出来
          【解决方案5】:

          这将创建一个长字符串,每一行都与字符串“”(一个空格)分开:

          public String ReadBigStringIn() {
              StringBuffer line = new StringBuffer();
          
          
              try { 
                  while(buffIn.ready()) {
                  line.append(" " + buffIn.readLine());
              } catch(IOException e){
                  e.printStackTrace();
              }
          
              return line.toString();
          }
          

          【讨论】:

            【解决方案6】:

            您有一个包含双打的文件。看起来每行有多个数字,并且可能有多行。

            最简单的做法是在 while 循环中读取行。

            您可以在到达最后一行时从您的 ReadBigStringIn 方法返回 null 并在那里终止您的循环。

            但更正常的做法是在一种方法中创建和使用阅读器。也许您可以更改为读取文件并返回数组或双精度列表的方法。

            顺便说一句,你能简单地用空格分割你的字符串吗?

            将整个文件读入单个字符串可能适合您的特定情况,但请注意,如果您的文件非常大,它可能会导致内存爆炸。对于此类 i/o,流式处理方法通常更安全。

            【讨论】:

              【解决方案7】:

              我强烈建议在这里使用库,但从 Java 8 开始,您也可以使用流来做到这一点。

                  try (InputStreamReader in = new InputStreamReader(System.in);
                       BufferedReader buffer = new BufferedReader(in)) {
                      final String fileAsText = buffer.lines().collect(Collectors.joining());
                      System.out.println(fileAsText);
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              

              您还可以注意到它非常有效,因为 joining 在内部使用 StringBuilder

              【讨论】:

              • 这是一个很棒的单行器,而不必迭代缓冲区、检查 null、tostring 等。
              • 如果你想保留行尾,你可以添加 System.lineSeparator() 作为 Collectors.joining 的参数: buffer.lines().collect( Collectors.joining( System.lineSeparator() ) )
              猜你喜欢
              • 2013-09-26
              • 1970-01-01
              • 2013-01-16
              • 2013-01-08
              • 2011-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-08-05
              • 1970-01-01
              相关资源
              最近更新 更多