Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newline character omitted while reading from buffer

Tags:

People also ask

Does BufferedReader read newline?

BufferedReaderThe readLine() method reads a line of text from the file and returns a string containing the contents of the line, excluding any line-termination characters or null.

Does readLine include newline?

The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end.

How do I stop Scanf from going to the next line?

For a simple solution, you could add a space before the format specifier when you use scanf(), for example: scanf(" %c", &ch); The leading space tells scanf() to skip any whitespace characters (including newline) before reading the next character, resulting in the same behavior as with the other format specifiers.

Does fgets read newline?

The fgets() function stores the result in string and adds a NULL character (\0) to the end of the string. The string includes the newline character, if read.


I've written the following code:

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();
  }

 }
}

When I execute the above code, following is the output:

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

Why are the newline characters (\n) skipped? If I uncomment the System.out.println() as following:

while ((line = bufferedReader.readLine()) != null) {
        System.out.println(line);
        sb.append(line);
       }

I get the correct output as:

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

What is reason for this?