【问题标题】:BufferedWriter.newLine() except after the last lineBufferedWriter.newLine() 除了最后一行之后
【发布时间】:2018-10-29 13:16:54
【问题描述】:

我在这上面画了一个空白。我面临的问题是我不希望在将最后一行写入新文件后创建newLine()。我怎样才能做到这一点?

while (((aLine = reader.readLine()) != null)) {
                writer.write(aLine);
                writer.newLine();
            }

【问题讨论】:

  • 切换它并在除第一行之外的每一行之前执行newLine()。很难判断您何时处于最后一行,但应该很容易判断哪一行是第一行。
  • @Thomas:这不会在第一行之前生成一个额外的新行吗?
  • @PushpeshKumarRajwanshi 好吧,我写了“...除了第一个”。那不应该在第一行之前创建一个新行。 ;)
  • 哦,好吧,对不起,除了第一个,我没有意识到你提到过。这样你是对的。
  • 感谢您的意见,伙计们。 tevemadar 的回答似乎对我来说完美地表达了这一点:)

标签: java bufferedwriter


【解决方案1】:

因为你看不到未来,你必须依赖过去:而不是在最后一行之后发出换行符,而是在除第一行之外的所有行之前发出它:

bool first=true;
while (((aLine = reader.readLine()) != null)) {
    if(!first)writer.newLine();
    else first=false;
    writer.write(aLine);
}

【讨论】:

  • “因为你看不到未来” - 我喜欢 :)
  • @Thomas 我也喜欢 :) 感谢 tevemadar 的口才和帮助。
【解决方案2】:
boolean flag = false;
while (((aLine = reader.readLine()) != null)) {
    if(flag)
        writer.newLine();
    writer.write(aLine);
    flag = true;
}

【讨论】:

    【解决方案3】:

    作为现有答案的细微变化(建议先写换行符):

    String separator = "";
    while (((aLine = reader.readLine()) != null)) {
      writer.write(separator);
      writer.write(aLine);
      separator = System.lineSeparator();
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-31
      • 2020-01-05
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多