如何使用Java检查文件中存储的文本是否包含换行符(Enter)?

Dev*_*nki 0 java newline

我正在尝试读取存储在文本文件中的数据,并检查文件的数据是否包含换行符。例如:如果文件包含数据:

This is first line.
This is second line.
Run Code Online (Sandbox Code Playgroud)

然后我的程序应该说第一行包含换行符。

我尝试使用

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");
}
Run Code Online (Sandbox Code Playgroud)

我也尝试了这段代码

while ((line = bufferedReader.readLine()) != null)
{
    if (line.contains(System.getProperty("line.separator")))
        System.out.println("Contains new line");
}
Run Code Online (Sandbox Code Playgroud)

但无济于事。

我的文件确实包含换行符。在记事本++中,如果我搜索\ n或\ r \ n,那么它的确会在文件中显示换行符。但是有些我的代码无法识别它。

Zel*_*don 5

如您所读BufferedReader#readLineJavaDoc

公共字符串readLine()引发IOException

读取一行文本。一行被认为由换行符('\ n'),回车符('\ r')或回车符后立即换行符中的任何一个终止。

返回值:

一个字符串,其中包含行的内容,不包含任何行终止符;如果已到达流的末尾,则为null

这就是为什么您的行没有行尾。