Currently I\'m using something like :
String[]lines = textContent.split(System.getProperty(\"line.separator\"));
for(String tmpLine : lines){
//do somethi
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(";"));
Combine java.io.StringReader
and java.io.LineNumberReader
You can actually wrangle Scanner
to allow you to use a normal for
loop:
import java.util.Scanner;
public class IterateLines {
public static void main(String[] args) {
Iterable<String> sc = () ->
new Scanner("foo bar\nbaz\n").useDelimiter("\n");
for (String line: sc) {
System.out.println(line);
}
}
}
gives us:
$ javac IterateLines.java && java IterateLines
foo bar
baz