有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

This is first line.
This is second line.

然后我的程序应该说第一行包含新行字符

我试着用

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");
}

我也试过这个代码

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

但没有用

我的文件不包含新行字符。在notepad++中,如果搜索\n或\r\n,它会在文件中显示新行字符。但有些人认为我的代码无法识别它


共 (1) 个答案

  1. # 1 楼答案

    正如你可以从BufferedReader#readLineJavaDoc中读到的那样

    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

    这就是为什么你的行没有行尾