我编写了以下代码:
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();
}
}
}
当我执行上面的代码时,输出如下:
This is the data to write in buffer!This is the second lineThis is the third line
为什么会跳过换行符 (\n)?如果我取消注释System.out.println()如下:
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 Says
public String readLine()
throws IOException
读取一行文本。一行被视为由换行符 ('\n')、回车符 ('\r') 或回车符后紧跟换行符之一终止。
Returns:
包含行内容的字符串,不包括任何行终止字符,如果已到达流末尾,则返回 null
投掷:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)