Why do we add \n
while reading JSON
data with a BufferedReader
?
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while((line = reader.readLine())!=null){
sb.append(line + "\n");
}
You're not adding a \n
- you're putting a line break back which readLine()
effectively swallowed. For example, if your text file initially consists of 5 lines:
line1
line2
line3
line4
line5
then reader.readLine()
will return (in successive calls) "line1"
, "line2"
, "line3"
, "line4"
, "line5"
... without the line ending at which BufferedReader
detected the end of the line.
So if you just had sb.append(line)
, you'd end up with a StringBuilder
containing:
line1line2line3line4line5
Having said that, the code seems somewhat pointless - it's really just normalizing the line breaks. Unless you actually need that, you might as well just use call read
instead of readLine()
and copy the text that way...
See more on this question at Stackoverflow