The specific issue is this: I am writing to a file and want to output a new line after each line written. If I use a normal loop without any further checks, this will create a blank line at the very end of the file for no reason. So I need to do this every time except the last one.
Despite the fact that this is a specific problem, I'm actually looking for a better general coding practice to deal with scenarios like this, since it isn't the first and won't be the last time I have to deal with it.
Here's my unsatisfying solution:
//Write contents to the file
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
for(int i = 0; i < lines.size(); i++) {
writer.write(lines.get(i));
if(i < lines.size() - 1) writer.newLine();
}
It seems wasteful to check the conditions twice through each iteration of the loop, and I feel like there ought to be a better way to accomplish what I want without the vague code smell. Anyone have any cool tips or tricks to make this more elegant?
It also prevents me from using an enhanced for
loop, which makes me sad.
lines
is a List<String>
.
Also, for those saying I should just join all the String
s with \n
, that's not an adequate solution. Firstly, it doesn't actually address the general coding practice. Secondly, when writing to a file with a BufferedWriter
, it's important to use newLine()
rather than writing a \n
.
?>
, it will be copied to the output and probably wind up in a place where the XML parser doesn't like it. So it's not by any means a hard rule. \$\endgroup\$