What is the best way to iterate over the lines of a Java String?
You could use :
BufferedReader bufReader = new BufferedReader(new StringReader(textContent));
And use the readLine()
method :
String line=null;
while( (line=bufReader.readLine()) != null )
{
}
To add the Java 8 way to this question:
Arrays.stream(content.split("\\r?\\n")).forEach(line -> /*do something */)
Of curse you can also use System.lineSeparator()
to split if you are sure that the file is comming from the same plattform as the vm runs on.
Or even better use the stream api even more agressiv with filter, map and collect:
String result = Arrays.stream(content.split(System.lineSeparator()))
.filter(/* filter for lines you are interested in*/)
.map(/*convert string*/)
.collect(Collectors.joining(";"));