简体   繁体   中英

Java iterate through a file, to append each line to make one big string

i want to able to get add each line to a string. like this format String = ""depends" line1 line2 line3 line4 line5 /depends""

so in essensce i want to itereate over each line and from "depends" to "/depends" including them from end to to end in a string. How do i go about to doing this?

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


<depends>
line1
line2
line3
line4
line5
line6
</depends
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();

In java != wouldn't work for String so you have to use while(!nextLine.equals("</depends>") . Also it is better to use StringBuilder and append new line to it than using String . String in java is immutable and because of that, StringBuilder is highly recommended in your case.

This is a general answer for any input file, but if your input file is xml there are many good java libraries for that.

If you could use java 8

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

quite nice version ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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