从缓冲区读取时忽略了换行符

11

我编写了以下代码:

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

这是什么原因?


取消注释 System.out.println(line); 并不能得到正确的输出,因为 System.out.println 会打印带有换行符的字符串。尝试将其替换为 System.out.print(line); - Clyde Lobo
7个回答

23

JavaDoc 提到

public String readLine()
                throws IOException

读取一行文本。一行被认为是由换行符('\n')、回车符('\r')或者回车符后面紧跟着的换行符之一结束。
返回值:
包含该行内容的字符串,不包括任何行终止字符,如果流已经结束则返回null
抛出异常:


3
@jigar,你知道有哪些阅读器可以读取包括换行符在内的每一行吗? - Juzer Ali
2
@Elliot,你可以使用read()方法逐个字符地读取文本。read() - jmj

9

来自Javadoc

读取一行文本。一行被认为是以换行符('\n')、回车符 ('\r') 或回车符后紧接着的换行符终止。

您可以这样做:

buffer.append(line);
buffer.append(System.getProperty("line.separator"));

3

以防有人想要包含'\n'的文本进行阅读。

可以尝试这种简单方法

那么,

假设你有三行数据(例如在一个.txt文件中),就像这样:

This is the data to write in buffer!
This is the second line
This is the third line

在阅读时,您就像这样做。

    String content=null;
    String str=null;
    while((str=bufferedReader.readLine())!=null){ //assuming you have 
    content.append(str);                     //your bufferedReader declared.
    }
    bufferedReader.close();
    System.out.println(content);

并且期望输出结果

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

以下是您可以做的事情

通过在while循环内添加此代码片段

if(str.trim().length()==0){
   content.append("\n");
}

现在你的while循环应该长成这样

while((str=bufferedReader.readLine())!=null){
    if(str.trim().length()==0){
       content.append("\n");
    }
    content.append(str);
}

现在您可以获得所需的输出(作为三行文本)。
This is the data to write in buffer!
This is the second line
This is the third line

1

这是 BufferedReader 类的 readLine() 方法 javadocs 所述内容

 /**
 * 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.
 *
 * @return     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
 *
 * @exception  IOException  If an I/O error occurs
 */

0

readline() 不会返回平台的行结尾。JavaDoc


0
这是因为readLine()。来自Java Docs

读取一行文本。一行被认为是由任何一个换行符('\n')、回车符('\r')或者紧接着回车符的换行符终止。

所以发生的情况是你的"\n"被视为换行符,因此阅读器将其视为一行。

0

我曾经遇到过一个类似的问题,使用ByteArrayInputStream从数据库中将文件内容作为字节数组加载,并通过IOUtils.readlines()读取。

我遇到的问题是由于反斜杠字符'\'被读取为换行符'\n'的单独字符,因此它将整个内容返回为一行。以下是示例文件记录:

"Header\\nRow1\\nRow2"

我不得不编写单独的代码,通过将字节数组转换为字符串进行字符替换,然后再从新形成的字符串将其转换回字节数组,以将字符从'\\n'替换为'\n',这对我有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接