问题
So My code looks like this:
try {
while ((line = br.readLine()) != null) {
Matcher m = urlPattern.matcher (line);
while (m.find()) {
System.out.println(m.group(1));
//the println puts linebreak after each find
String filename= "page.txt";
FileWriter fw = new FileWriter(filename,true);
fw.write(m.group(1));
fw.close();
//the fw writes everything after each find with no line break
}
}
I get right form of output at line System.out.println(m.group(1)); However when I later on want to write what is shown by m.group(1) It writes to file without putting linebreak since the code doesn't have one.
回答1:
Just call fw.write(System.getProperty("line.separator"));.
System.getProperty("line.separator") will give you the line separator for your platform (whether Windows or some Unix flavor).
回答2:
println(text) adds the line break to the string, and is essentially the same as print(text); print(System.getProperty("line.separator"));.
So in order to add the line break you have to do the same.
However, to improve your code, I have two recommendations:
- Don't create a new
FileWriterin the loop. Create it outside the loop and close it after the loop. - Don't use a
FileWriter, but instead aPrintWriterwrapped around aFileWriter. Then you get the sameprintln()method asSystem.out.
回答3:
just do
fw.write("\n");
that will put an escape character for a new line
回答4:
You can use instead System.getProperty("line.separator") also System.lineSeparator()
来源:https://stackoverflow.com/questions/17716192/insert-line-break-when-writing-to-file