Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

We have a Java Application that has a few modules that know to read text files. They do it quite simply with a code like this:

BufferedReader br = new BufferedReader(new FileReader(file));   String line = null;   while ((line = br.readLine()) != null)   {      ... // do stuff to file here   }  

I ran PMD on my project and got the 'AssignmentInOperand' violation on the while (...) line.

Is there a simpler way of doing this loop other than the obvious:

String line = br.readLine();   while (line != null)   {      ... // do stuff to file here      line = br.readLine();   }  

Is this considered a better practice? (although we "duplicate" the line = br.readLine() code?)

like image 324
RonK Avatar asked Jan 13 '11 06:01

RonK


People also ask

What is the easiest way to read text files line by line in Java 8?

Java 8 has added a new method called lines() in the Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed.

Which method is used in Java to read line from text file?

We can use java. io. BufferedReader readLine() method to read file line by line to String.


1 Answers

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

like image 73
Leonardo Brambilla Avatar answered Sep 17 '22 17:09

Leonardo Brambilla