Iterating over the content of a text file line by line - is there a best practice? (vs. PMD's AssignmentInOperand) Iterating over the content of a text file line by line - is there a best practice? (vs. PMD's AssignmentInOperand) java java

Iterating over the content of a text file line by line - is there a best practice? (vs. PMD's AssignmentInOperand)


I know is an old post but I just had the same need (almost) and I solve it using a LineIterator from FileUtils in Apache Commons.From their javadoc:

LineIterator it = FileUtils.lineIterator(file, "UTF-8");try {    while (it.hasNext()) {    String line = it.nextLine();    // do something with line    }} finally {    it.close();}

Check the documentation: http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/LineIterator.html


The support for streams and Lambdas in java-8 and Try-With-Resources of java-7 allows you to achive what you want in more compact syntax.

Path path = Paths.get("c:/users/aksel/aksel.txt");try (Stream<String>  lines = Files.lines(path)) {    lines.forEachOrdered(line->System.out.println(line));} catch (IOException e) {    //error happened}


I generally prefer the former. I don't generally like side-effects within a comparison, but this particular example is an idiom which is so common and so handy that I don't object to it.

(In C# there's a nicer option: a method to return an IEnumerable<string> which you can iterate over with foreach; that isn't as nice in Java because there's no auto-dispose at the end of an enhanced for loop... and also because you can't throw IOException from the iterator, which means you can't just make one a drop-in replacement for the other.)

To put it another way: the duplicate line issue bothers me more than the assignment-within-operand issue. I'm used to taking in this pattern at a glance - with the duplicate line version I need to stop and check that everything's in the right place. That's probably habit as much as anything else, but I don't think it's a problem.