因此,当我尝试对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)来写句子,然后再换行...