【问题标题】:Java iterate through a file, to append each line to make one big stringJava 遍历文件,追加每一行以生成一个大字符串
【发布时间】:2014-10-27 14:00:20
【问题描述】:

我希望能够将每一行添加到一个字符串中。 像这种格式 String = ""depends" line1 line2 line3 line4 line5 /depends""

所以本质上我想遍历每一行并从“depends”到“/depends”,包括它们在一个字符串中从头到尾。我该怎么做呢?

 while(nextLine != "</depends>"){
    completeString = line + currentline;
}


<depends>
line1
line2
line3
line4
line5
line6
</depends

【问题讨论】:

  • while(!"&lt;/depends&gt;".equals(nextLine)) {
  • 旁注:使用 StringBuilder 而不是普通的字符串连接。它会更快,而且你不会用未使用的字符串浪费内存。
  • 如果您使用的是 xml,您可以使用 dom 解析器。前任。 Dom4j
  • @stuXnet 需要注意的是,字符串连接在幕后使用了字符串生成器。
  • @DaveNewton 是也不是,iirc。实际上,line + currentline 会变成new StringBuilder().append(line).append(currentline).toString() 或类似的东西,但Java 不会在所有迭代中使用相同的StringBuilder,而是每次都创建一个新的。所以如果你使用循环,你应该使用StringBuilder

标签: java


【解决方案1】:
final BufferedReader br = new BufferedReader(new FileReader("path to your file"));
final StringBuilder sb = new StringBuilder(); 
String nextLine = br.readLine();//skip first <depends>

while(nextLine != null && !nextLine.equals("</depends>"))//not the end of the file and not the closing tag
{
    sb.append(nextLine);
    nextLine = br.readLine();
}

final String completeString = sb.toString();

【讨论】:

  • +1 用于考虑nextLinenull
【解决方案2】:

如果你可以使用 java 8

Files
    .lines(pathToFile)
    .filter(s -> !s.equals("<depends>") && !s.equals("</depends>"))
    .reduce("", (a, b) -> a + b));

相当不错的版本;)

【讨论】:

    【解决方案3】:

    在 java 中,!= 不适用于 String,因此您必须使用 while(!nextLine.equals("&lt;/depends&gt;")。此外,使用StringBuilder 并在其上追加新行比使用String 更好。 String 在 java 中是 immutable,因此,强烈建议您使用 StringBuilder

    这是任何输入文件的一般答案,但如果您的输入文件是 xml,那么有很多很好的 java 库。

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 2021-06-30
      • 2010-11-30
      • 2014-06-29
      • 2020-02-02
      • 2023-03-30
      • 2015-02-08
      • 2015-08-27
      相关资源
      最近更新 更多