Java遍历文件,追加每一行以生成一个大字符串

时间:2014-10-27 14:00:21

标签: java

我希望能够将每一行添加到字符串中。 像这样的格式String =“”取决于“line1 line2 line3 line4 line5 / depends”“

所以在本质上我想迭代每一行,从“依赖”到“/依赖”,包括它们在字符串中从头到尾。我该怎么做呢?

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


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

3 个答案:

答案 0 :(得分:2)

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 :(得分:1)

在java中!=不适用于String,因此您必须使用while(!nextLine.equals("</depends>")。此外,最好使用StringBuilder并为其添加新行,而不是使用String。 java中的Stringimmutable,因此,在您的情况下强烈建议使用StringBuilder

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

答案 2 :(得分:1)

如果你可以使用java 8

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

相当不错的版本;)