Search code examples
javajspwritetofile

Java/JSP: Preserve line breaks while writing to a local file from string variables


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.


Solution

  • 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);