Java:如何通过忽略"\ n"来逐行读取文件 [英] Java: How read a File line by line by ignoring "\n"

查看:579
本文介绍了Java:如何通过忽略"\ n"来逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试逐行读取制表符分隔的文本文件行.通过使用回车符("\ r \ n")分隔行,并且在制表符分隔的文本字段中允许使用LineFeed(\"n").

I'm trying to read a tab separated text file line per line. The lines are separated by using carriage return ("\r\n") and LineFeed (\"n") is allowed within in tab separated text fields.

由于我要读取每行的文件行,因此我希望程序忽略独立的"\ n". 不幸的是,BufferedReader使用两种可能性来分隔行.我如何修改我的代码,以忽略独立的"\ n"?

Since I want to read the File Line per Line, I want my programm to ignore a standalone "\n". Unfortunately, BufferedReader uses both possibilities to separate the lines. How can I modify my code, in order to ignore the standalone "\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);
}

这篇关于Java:如何通过忽略"\ n"来逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆