Newline character omitted while reading from buffer

前端 未结 6 2069
一个人的身影
一个人的身影 2021-01-11 16:22

I\'ve written the following code:

public class WriteToCharBuffer {

 public static void main(String[] args) {
  String text = \"This is the data to write in          


        
6条回答
  •  一整个雨季
    2021-01-11 17:17

    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
    

提交回复
热议问题