purplehaze
purplehaze

Reputation: 33

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

Upvotes: 0

Views: 1073

Answers (3)

Lrrr
Lrrr

Reputation: 4807

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.

Upvotes: 1

Koziołek
Koziołek

Reputation: 2874

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 ;)

Upvotes: 1

ortis
ortis

Reputation: 2223

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();

Upvotes: 2

Related Questions