n_g
n_g

Reputation: 3545

Newline character omitted while reading from buffer

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?

Upvotes: 11

Views: 33962

Answers (7)

Mohamed Yusuff
Mohamed Yusuff

Reputation: 121

I have faced a similar issue from a ByteArrayInputStream where the file contents are loaded as a byte array from the database and that's being read through IOUtils.readlines().

The issue that I faced is due to the backslash character '\' that's being read as a separate character from the newline character '\n', so it returns the entire content as a single line. An example file record as below.

"Header\\nRow1\\nRow2"

I had to write a separate code to replace the characters from '\\n' to '\n' by converting the byte array into string for the string replacements and again converted back to byte array from the newly formed string and that worked for me.

Upvotes: 0

eRaisedToX
eRaisedToX

Reputation: 3361

Just in case someone wants to read the text with '\n' included.

try this simple approach

So,

Say, You have three lines of data (say in a .txt file) , like this

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

And while reading, you are doing something like this

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

and expecting the output to be

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

but scratching your head upon seeing output as a single line

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

Here is what you can do

by adding this piece of code inside your while loop

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

So now what your while loop should look like

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

Now you get required output (as three lines of text)

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

Upvotes: 3

Clyde Lobo
Clyde Lobo

Reputation: 9174

This is what the javadocs says for the readLine() method of class 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
 */

Upvotes: 1

user467871
user467871

Reputation:

From Javadoc

Read 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.

You can do something like that

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

Upvotes: 9

CoolBeans
CoolBeans

Reputation: 20800

This is because of readLine(). From Java Docs:

Read 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.

So what is happening is your "\n" are being considered as a line feed so reader considers that to be a line.

Upvotes: 0

Uriah Carpenter
Uriah Carpenter

Reputation: 6726

readline() does not return the platforms line ending. JavaDoc.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240870

JavaDoc Says

public String readLine()
                throws IOException

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.
Returns:
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
Throws:

Upvotes: 23

Related Questions