Java在句子后添加新行(为什么要加倍新行来解决)?

因此,当我尝试对IOFile进行一些练习时,我遇到了一个在txt文件上写字符串的问题,特别是在新文件中的每个句子之后写新行(\ n)的问题。

这是我的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main {
 public static void main(String[] args) {

    File Lyrics = new File("Lyrics.txt");
    File output = new File ("output.txt");

    try {
        Scanner myReader = new Scanner (Lyrics);
        try {
            FileWriter FBI = new FileWriter(output);
            while (myReader.hasnextLine()) {
                FBI.write(myReader.nextLine());
                FBI.write("\n");
            }
            FBI.close();
        }catch (IOException e) {}
        myReader.close();
    }catch (FileNotFoundException e) {}
  }
}

Lyrics.txt:

I could never find the right way to tell you
Have you noticed I've been gone
Cause I left behind the home that you made me
But I will carry it along

输出:

I could never find the right way to tell you
Have you noticed I've been gone
Cause I left behind the home that you made me
But I will carry it along
***invisible new line here

要求的锻炼结果:

I could never find the right way to tell you

Have you noticed I've been gone

Cause I left behind the home that you made me

But I will carry it along
***invisible new line here

尝试添加新的代码行并找出问题所在之后,我简单地修复了更改代码行的问题,即在

中添加了新行。
FBI.write("\n\n");

但是我仍然感到困惑,为什么我必须添加双换行(\ n \ n)来写句子,然后再换行...

panlikq 回答:Java在句子后添加新行(为什么要加倍新行来解决)?

\n表示换行符。

如果我的文字是

FooBar\nHello World

我会收到

FooBar
Hello World

由于\n(换行符)使我们的HelloWorld换行了,所以一切正确。 但是,您需要使用两行新的行(当前行+一空白行)而不是一行,则必须使用\n\n

输入

FooBar\n\nHello World

输出

FooBar

Hello World
,

\n换行符立即在前一行下方开始没有间隔的新行。如果要在句子之间留空行,则需要添加第二个\n来创建间隔。

本文链接:https://www.f2er.com/2556832.html

大家都在问