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?
readline()
does not return the platforms line ending. JavaDoc.This is because of readLine(). From Java Docs:
So what is happening is your "\n" are being considered as a line feed so reader considers that to be a line.
JavaDoc Says
From Javadoc
You can do something like that
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 thisAnd while reading, you are doing something like this
and expecting the output to be
but scratching your head upon seeing output as a single line
Here is what you can do
by adding this piece of code inside your while loop
So now what your
while
loop should look likeNow you get required output (as three lines of text)
This is what the javadocs says for the readLine() method of class BufferedReader