2

I'm drawing a blank on this. The problem I'm facing is I don't want a newLine() created after the last line is written to the new file. How can I accomplish this?

while (((aLine = reader.readLine()) != null)) {
                writer.write(aLine);
                writer.newLine();
            }
notAChance
  • 1,360
  • 4
  • 15
  • 47

3 Answers3

4

As you can not see the future, you have to rely on the past: instead of emitting a newline after the last line, emit it before all lines, except the first one:

bool first=true;
while (((aLine = reader.readLine()) != null)) {
    if(!first)writer.newLine();
    else first=false;
    writer.write(aLine);
}
tevemadar
  • 12,389
  • 3
  • 21
  • 49
0
boolean flag = false;
while (((aLine = reader.readLine()) != null)) {
    if(flag)
        writer.newLine();
    writer.write(aLine);
    flag = true;
}
Jignesh M. Khatri
  • 1,407
  • 1
  • 14
  • 22
0

As a slight variation on the existing answers (which propose writing the newline first):

String separator = "";
while (((aLine = reader.readLine()) != null)) {
  writer.write(separator);
  writer.write(aLine);
  separator = System.lineSeparator();
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243