Символ новой строки пропускается при чтении из буфера

Я написал следующий код:

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

В чем причина этого?


person n_g    schedule 28.01.2011    source источник
comment
Раскомментирование System.out.println(line); не дает правильного вывода, потому что System.out.println prints строка с новой строкой. Попробуйте заменить его на System.out.print(line);   -  person Clyde Lobo    schedule 28.01.2011


Ответы (6)


JavaDoc говорит

public String readLine()
                throws IOException

Читает строку текста. Строка считается завершенной одним из следующих символов: перевод строки ('\n'), возврат каретки ('\r') или возврат каретки, за которым сразу следует перевод строки.
Возвраты:< /strong>
Строка, содержащая содержимое строки, не включая символы завершения строки, или null, если достигнут конец потока
Выдает:

person jmj    schedule 28.01.2011
comment
@jigar, вы знаете какой-нибудь ридер, который может читать строку вместе с символом новой строки? - person Juzer Ali; 19.01.2013
comment
@Elliot, вы можете читать char за char read() - person jmj; 16.03.2017

Из Javadoc

Прочитайте строку текста. Строка считается завершенной одним из следующих символов: перевод строки ('\n'), возврат каретки ('\r') или возврат каретки, за которым сразу следует перевод строки.

Вы можете сделать что-то подобное

buffer.append(line);
buffer.append(System.getProperty("line.separator"));
person Community    schedule 28.01.2011

На всякий случай, если кто-то захочет прочитать текст с включенным '\n'.

попробуйте этот простой подход

So,

Скажем, у вас есть три строки данных (скажем, в файле .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
person eRaisedToX    schedule 26.04.2017

Это то, что говорит javadocs для метода readLine() класса BufferedReader

 /**
 * 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
 */
person Clyde Lobo    schedule 28.01.2011

readline() не возвращает окончание строки платформы. JavaDoc .

person Uriah Carpenter    schedule 28.01.2011