[英]java read properties and xml file using stringbuilder
I need to read a set of xml and property files and parse the data. 我需要读取一组xml和属性文件并解析数据。 Currently I am using inputstream ans string builder to do this.
目前,我正在使用inputstream ans字符串生成器来执行此操作。 But this does not create the file in the same way as input file is.
但这不会以与输入文件相同的方式创建文件。 I donot want to remove the white spaces and new lines.
我不想删除空格和换行。 How do i achieve this.
我该如何做到这一点。
is = test.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String line5;
StringBuilder sb5 = new StringBuilder();
while ((line5 = br.readLine()) != null) {
sb5.append(line5);
}
String s = sb5.toString();
My output is: 我的输出是:
#test 123 #test2 345
Expected output is: 预期输出为:
#test
123
#test2
345
Any thoughts ? 有什么想法吗 ? Thanks
谢谢
br.readLine() consumes the line breaks, you need to add them to your StringBuilder after appending the line. br.readLine()使用换行符,您需要在添加换行符后将它们添加到StringBuilder中。
is = test.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String line5;
StringBuilder sb5 = new StringBuilder();
while ((line5 = br.readLine()) != null) {
sb5.append(line5);
sb5.append("\n");
}
If you want an extremely simple solution for reading a file to a String, Apache Commons-IO has a method for performing such a task ( org.apache.commons.io.FileUtils ). 如果您想要一个非常简单的解决方案来将文件读取为String,则Apache Commons-IO提供了一种用于执行此类任务的方法( org.apache.commons.io.FileUtils )。
FileUtils.readFileToString(File file, String encoding);
readLine()
method doesn't add the EOL character (\\n). readLine()
方法不添加EOL字符(\\ n)。 So while appending the string to the builder, you need to add the EOL char, like sb5.append(line5+"\\n");
因此,在将字符串附加到生成器时,您需要添加EOL字符,例如
sb5.append(line5+"\\n");
The various readLine
methods discard the newline from the input. 各种
readLine
方法从输入中丢弃换行符。
From the BufferedReader
docs : 从
BufferedReader
docs中 :
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
返回:包含行内容的String,不包含任何行终止字符;如果已到达流的末尾,则返回null
A solution may be as simple as adding back a newline to your StringBuilder
for every readLine
: sb5.append(line5 + "\\n");
一个解决方案可能很简单,就是为每个
readLine
重新向StringBuilder
添加换行: sb5.append(line5 + "\\n");
. 。
A better alternative is to read into an intermediate buffer first, using the read
method, supplying your own char[]
. 更好的选择是使用
read
方法首先读取中间缓冲区,并提供您自己的char[]
。 You can still use StringBuilder.append
, and get a String will match the file contents. 您仍然可以使用
StringBuilder.append
,并获取一个与文件内容匹配的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.