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

博主尝试逐行读取以制表符分隔的文本文件,文件行以回车分隔,允许制表符分隔的文本字段内有换行符,希望程序忽略单独的换行符,但BufferedReader会将两者都作为行分隔符。给出的解决方案是使用java.util.Scanner,设置分隔符为回车换行符来读取文件。

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.

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

}

解决方案

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值