如何在String readAllBytes中保留换行符
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在String readAllBytes中保留换行符相关的知识,希望对你有一定的参考价值。
乡亲
我使用的模板文件将被送入String变量,但是当我写入字符串的内容时,它会忽略文件中的换行符。
如何保留原始文件中的换行符,以便输出文件还包含这些换行符?
码
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));
模板文件(帮助那些无法重现的人)
<!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>
答案
有问题:
StringBuilder result = new StringBuilder("");
String line;
while ((line = reader.readLine()) != null) { // <---
result.append(line);
}
in.close();
BufferedReader::readLine
读取一行,但不是行结尾:
返回:包含行内容的String,不包括任何行终止字符
如果你想读取一个文件,同时也以行结尾结束,你可以这样做:
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);
}
只需在每个读取行后添加newLineChar ...
以上是关于如何在String readAllBytes中保留换行符的主要内容,如果未能解决你的问题,请参考以下文章
JavaFiles.readAllBytes(Path) 遇见的坑
如何在 linq 中展平字典<string,List<string>> 并在结果中保留键
为啥 File.ReadAllBytes 结果与使用 File.ReadAllText 时不同?