Java: How read a File line by line by ignoring “\\n”

陌路散爱 提交于 2019-12-03 03:46:36

Use a 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);
}

You could simply make it skip empty lines:

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

You can use FileUtils.readLines methods from apache commons-io.

Advantage of using it is that you don't have to care about opening and closing file. It is handled for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!