Символ новой строки опущен при чтении из буфера
Я написал следующий код:
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
В чем причина этого?
Ответы
Ответ 1
JavaDoc Говорит
public String readLine()
throws IOException
Считывает текст. Линия считается завершенной любым одним строком строки ('\n'), возвратом каретки ('\ r') или возвратом каретки, с которым немедленно следует строка. Возврат:
Строка, содержащая содержимое строки, не включая символы окончания строки, или значение null, если конец потока достигнут
Броски:
Ответ 2
От 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
Ответ 4
Это то, что 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
*/
Ответ 5
readline()
не возвращает окончание строки платформ. JavaDoc.
Ответ 6
Это из-за readLine(). Из Документы Java:
Прочитайте строку текста. Линия считается прекращенным любым строки ('\n'), каретки return ('\ r') или возврат каретки после чего сразу возвращается строка.
Итак, что происходит, ваш "\n" рассматривается как линейный канал, поэтому читатель считает, что это строка.