简体   繁体   中英

How to preserve line break in String readAllBytes

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>

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();
        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...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM