In Java, readLine()
uses \n
and \r
as line feed and carriage return end characters to determine the next lines. So, when you use readLine()
, then you won't get \n
or \r
characters to be displayed in the console as these characters will be masked by the readLine()
. For more information about readLine()
, refer to the official Oracle doc.
To avoid such behavior, we should use read()
method from BufferedReader
package. The following sample snippet will help to understand how these \n
and \r
are getting recognized using read()
.
Let's say you have a file called test_lineFeed.txt which contains line breaks, and if you want to replace them with some defined format like "CR-LF" (CR --> Carriage return, LF --> Line Feed), then use the following snippet.
BufferedReader reader1 = new BufferedReader(
new InputStreamReader(
new FileInputStream("/home/test_lineFeed.txt")
));
int s1 = 0;
String formattedString = "";
while ((s1 = reader1.read()) != -1) {
char character = (char) s1;
System.out.println("Each Character: "+character+" its hexacode(Ascii): "+Integer.toHexString(character));
//output : "0a" --> \n
//output : "0d" --> \r
if (character == '\n'){
formattedString+=" <LF> ";
}else if (character =='\r'){
formattedString+=" <CR> ";
}else
formattedString+=character;
}
System.out.println(formattedString);