我试图读取存储在文本文件中的数据,并检查文件的数据是否包含换行符。 例如:if file包含数据:
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,那么它会在文件中显示新行字符。但有些我的代码没有认识到它。
答案 0 :(得分:5)
正如您可以从BufferedReader#readLine
JavaDoc
public String readLine()抛出IOException
读取一行文字。一条线被认为是由换行符('\ n'),回车符('\ r')或回车符后面的任何一个终止。
返回:
包含行内容的字符串,不包括任何行终止字符;如果已到达流的末尾,则为null
这就是为什么你的专线没有行结尾。