0

Folks

I am using a template file which will be fed into a String variable, however when i write the contents of the string it ignores the linebreaks in the file.

How do i preserve the line breaks from original file so the output file also contains these line breaks ?

Code

      InputStream in = classLoader.getResourceAsStream("templates/reportTemplate.html");
      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
      //File htmlTemplateFile = new File();
     // String htmlString = FileUtils.read(classLoader.getResourceAsStream("templates/reportTemplate.html");)
      String body = data;
      StringBuilder result = new StringBuilder("");
      String line;
      while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        in.close();

          File newHtmlFile = new File(fileLocation + "/report.html");
          FileUtils.writeStringToFile(newHtmlFile, result.toString().replace("$body", body));
          Path path = Paths.get(fileLocation + "/report.html");
          Charset charset = StandardCharsets.ISO_8859_1;

          String content = new String(Files.readAllBytes(path),charset);
          // Not working :: String newLineChar = System.getProperty("line.separator");
          // Not working :: content = content.replaceAll("\\n", newLineChar);
         content = content.replaceAll("\\$highrisk", Integer.toString(highrisk));
        content = content.replaceAll("\\$criticalrisk", Integer.toString(criticalrisk));
        content = content.replaceAll("\\$mediumrisk", Integer.toString(mediumrisk));
        content = content.replaceAll("\\$lowrisk", Integer.toString(lowrisk));
          Files.write(path, content.getBytes(charset));

Template file (to help those who cannot reproduce)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
 <script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

// Draw the chart and set the chart values
function drawChart() {
  var data = google.visualization.arrayToDataTable([
  ['Risk', 'Risk Meter'],
  ['Medium', $mediumrisk],
  ['Critical', $criticalrisk],
  ['High', $highrisk],
  ['Low', $lowrisk],
]);

  // Optional; add a title and set the width and height of the chart
  var options = {'title':'Risk Coverage', 'width':550, 'height':400};

  // Display the chart inside the <div> element with id="piechart"
  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  chart.draw(data, options);
}
</script>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>myAp Report</title>
</head>
<body>
<div class="container" style="float: left;"> 
  <h2>Report from myApp</h2>
  <p>This report contains summary of scan results from my app</p>
$body
</div>
<div id="piechart"></div>
</body>
</html>
Sudheej
  • 1,873
  • 6
  • 30
  • 57
  • FYI, you can use `replace("$highrisk"` instead of `replaceAll("\\$highrisk"`. – shmosel Dec 28 '17 at 00:41
  • 1
    I see no evidence there were newlines originally or that they were removed. Please provide a [mcve]. – shmosel Dec 28 '17 at 00:41
  • @shmosel the question is not about replacing the token, that works fine.Also this can be any file which has linebreaks but once its fed into String and written back to a file the Breaks are not preserved. – Sudheej Dec 28 '17 at 00:43
  • Which is why I prefaced my comment with "FYI". – shmosel Dec 28 '17 at 00:43
  • Can not reproduce. Reading from a file with line breaks and then writing back like you suggested preserves the line breaks. Are you sure you're using the right encoding everywhere? – Jorn Vernee Dec 28 '17 at 00:48
  • In html file line breaks are tagged. – Roman C Dec 28 '17 at 00:50
  • All, i have included the comments, the problem is Javascript is scrambled in the final output with no line breaks. – Sudheej Dec 28 '17 at 00:53
  • 1
    Still can't reproduce with this, you really need to provide a [mcve] – Jorn Vernee Dec 28 '17 at 00:56
  • I added the code which reads the template file, and i also added the code which outputs to a file along with the template files. This should suffice. – Sudheej Dec 28 '17 at 00:59
  • Much better. Next time please don't make us go through hoops to see your code. – shmosel Dec 28 '17 at 01:18

2 Answers2

2

There's the problem:

StringBuilder result = new StringBuilder("");
String line;
while ((line = reader.readLine()) != null) { // <---
    result.append(line);
}
in.close();

BufferedReader::readLine reads a line, but not the line ending:

Returns: A String containing the contents of the line, not including any line-termination characters

If you want to read a file while also ending up with the line endings you could do this:

InputStream in = classLoader.getResourceAsStream("templates/reportTemplate.html");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String result = reader.lines().collect(Collectors.joining(System.lineSeparator()));
reader.close();
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
0
        StringBuilder result = new StringBuilder();
        String line;
        String newLineChar = System.getProperty("line.separator");
        while ((line = reader.readLine()) != null) {
            result.append(line);
            result.append(newLineChar);
        }

just add newLineChar after every read line...

zlakad
  • 1,314
  • 1
  • 9
  • 16