所以,当我试图做一些关于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) {}
}
}
歌词.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("nn");
但我仍然很困惑,为什么我必须加一个双新行(\n\n(来写句子,然后加上新行。。。
n
表示新行。
所以如果我的文本是
FooBarnHello World
我会收到
FooBar
Hello World
由于n
(新线(使我们的HelloWorld
移动到新线,所以一切都是正确的。但是您想要两个新行(当前一行+一个空行(而不是一行,您必须使用nn
。
输入
FooBarnnHello World
输出
FooBar
Hello World
n
换行符在前一行的正下方开始一个新行,没有任何间隙。如果你想在句子之间留出一行空白,你需要再加一个n
来创造一个空白。