5

我正在尝试每行读取一个制表符分隔的文本文件行。使用回车符 ("\r\n") 分隔行,并且允许在制表符分隔的文本字段中使用换行符 (\"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();
}
4

3 回答 3

16

使用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);
}
于 2013-05-23T11:02:02.007 回答
0

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

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);
}
于 2013-05-23T10:58:25.260 回答
0

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

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

于 2013-05-23T11:08:42.857 回答