Reputation: 109
I'm trying to read data stored in text file and check if file's data contains new line character or not. For example: if file contains data:
This is first line.
This is second line.
Then my program should say that first line contains new line character.
I tried using
File file = new File(System.getProperty("user.dir") + File.separator + "test.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while ((line = bufferedReader.readLine()) != null)
{
char[] arr = line.toCharArray();
for(char test: arr)
if(String.valueOf(test) == System.getProperty("line.separator"))
System.out.println("Contains new line");
}
and I also tried this code
while ((line = bufferedReader.readLine()) != null)
{
if (line.contains(System.getProperty("line.separator")))
System.out.println("Contains new line");
}
but to no avail.
My file does contains new line character. In notepad++ if I search for \n or \r\n then it does shows new line character in file. But some how my code is not recognizing it.
Upvotes: 0
Views: 3720
Reputation: 5516
As you can read from the BufferedReader#readLine
JavaDoc
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
That is why your line has no line endings.
Upvotes: 5