Символ новой строки пропущен при чтении из буфера - PullRequest
10 голосов
/ 28 января 2011

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

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

В чем причина?

Ответы [ 6 ]

22 голосов
/ 28 января 2011

JavaDoc Говорит

public String readLine()
                throws IOException

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

8 голосов
/ 28 января 2011

С Javadoc

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

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

buffer.append(line);
buffer.append(System.getProperty("line.separator"));
3 голосов
/ 26 апреля 2017

На всякий случай, если кто-то захочет прочитать текст с включенным '\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 голос
/ 28 января 2011

Это то, что 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
 */
0 голосов
/ 28 января 2011

Это из-за readLine (). От Документы Java :

Читать строку текста. Линия считается прекращенным кем-либо перевода строки ('\ n'), каретка возврат ('\ r') или возврат каретки с последующим немедленным переводом строки.

То, что происходит, это то, что ваш "\ n" рассматривается как перевод строки, поэтому читатель считает, что это строка.

0 голосов
/ 28 января 2011

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

...