Reputation: 139
I need help to create read-write methods that write to a file and preserve the line breaks. The contents of the file are stored in a variable.
I use the following code to read a local HTML file:
public String scanLocalPage(String filePath) throws IOException
{
try{
BufferedReader reader = new BufferedReader(new FileReader(filePath));
StringBuilder sb = new StringBuilder();
String line;
while((line = reader.readLine())!= null){
sb=sb.append(line);
}
reader.close();
return sb.toString();
}
catch (Exception ee)
{
return "";
}
}
and the following method to write to a file:
public void writeToFile (String fileName, String fileContents) throws IOException
{
File outFile = new File (fileName);
try (FileWriter fw = new FileWriter(outFile)) {
fw.write(fileContents);
fw.close();
}
}
I use the above methods to read and write to a HTML file and a text file from String variables. The contents of the HTML file are generated in the code and the text file from a text area input field.
After writing to the file and then reading it again, the file contents are missing the line breaks. Any help to read/write with line breaks is appreciated.
Upvotes: 2
Views: 1386
Reputation: 4191
You should use the system-dependent line separator string:
On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".
String newLine = System.getProperty("line.separator");
sb = sb.append(line).append(newLine);
If you are using Java 7 or greater, you can use the System.lineSeparator() method.
String newLine = System.lineSeparator();
sb = sb.append(line).append(newLine);
Upvotes: 3
Reputation: 86774
When you use readline()
the line breaks are removed. You have to re-insert them with
sb = sb.append(line).append("\n");
Upvotes: 1