从缓冲区读取时省略了换行符 [英] Newline character omitted while reading from buffer
问题描述
我写了以下代码:
public class WriteToCharBuffer {
public static void main(String[] args) {
String text = "This is the data to write in buffer!\nThis is the second line\nThis is the third line";
OutputStream buffer = writeToCharBuffer(text);
readFromCharBuffer(buffer);
}
public static OutputStream writeToCharBuffer(String dataToWrite){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(byteArrayOutputStream));
try {
bufferedWriter.write(dataToWrite);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream;
}
public static void readFromCharBuffer(OutputStream buffer){
ByteArrayOutputStream byteArrayOutputStream = (ByteArrayOutputStream) buffer;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())));
String line = null;
StringBuffer sb = new StringBuffer();
try {
while ((line = bufferedReader.readLine()) != null) {
//System.out.println(line);
sb.append(line);
}
System.out.println(sb);
} catch (IOException e) {
e.printStackTrace();
}
}
}
当我执行上面的代码,以下是输出:
When I execute the above code, following is the output:
This is the data to write in buffer!This is the second lineThis is the third line
为什么跳过换行符(\ n)?如果我取消注释 System.out.println(),如下所示:
Why are the newline characters (\n) skipped? If I uncomment the System.out.println() as following:
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
sb.append(line);
}
我得到正确的输出:
This is the data to write in buffer!
This is the second line
This is the third line
This is the data to write in buffer!This is the second lineThis is the third line
这是什么原因?
推荐答案
JavaDoc 说
public String readLine()
throws IOException
读取一行文字。一条线被认为是换行符('\ n'),回车符('\ r')或回车符后面的任何一个终止。
返回:
包含行内容的字符串,不包括任何行终止字符;如果已到达流末尾,则为null
抛出:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
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
Throws:
这篇关于从缓冲区读取时省略了换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!