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.
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).
println(text)
adds the line break to the string, and is essentially the same as print(text); print(System.getProperty("line.separator"));
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:
FileWriter
in the loop. Create it outside the loop and close it after the loop. FileWriter
, but instead a PrintWriter
wrapped around a FileWriter
. Then you get the same println()
method as System.out
. just do
fw.write("\n");
that will put an escape character for a new line
您可以使用System.getProperty(“line.separator”)代替System.lineSeparator()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.