Java:如何通过忽略“\ n”逐行读取文件

我正在尝试每行读取一个制表符分隔的文本文件行。 使用回车符(“\ r \ n”)分隔行,并在制表符分隔的文本字段中允许使用LineFeed(\“n”)。

由于我想读取每行的文件行,我希望我的程序忽略一个独立的“\ n”。 不幸的是, BufferedReader使用两种可能性来分隔线。 如何修改我的代码,以便忽略独立的“\ n”?

 try { BufferedReader in = new BufferedReader(new FileReader(flatFile)); String line = null; while ((line = in.readLine()) != null) { String cells[] = line.split("\t"); System.out.println(cells.length); System.out.println(line); } in.close(); } catch (IOException e) { e.printStackTrace(); } 

使用java.util.Scanner

 Scanner scanner = new Scanner(new File(flatFile)); scanner.useDelimiter("\r\n"); while (scanner.hasNext()) { String line = scanner.next(); String cells[] = line.split("\t"); System.out.println(cells.length); System.out.println(line); } 

你可以简单地让它跳过空行:

 while ((line = in.readLine()) != null) { // Skip lines that are empty or only contain whitespace if (line.trim().isEmpty()) { continue; } String[] cells = line.split("\t"); System.out.println(cells.length); System.out.println(line); } 

您可以使用apache commons-io中的FileUtils.readLines方法。

使用它的好处是您不必关心打开和关闭文件。 它是为您处理的。