Java:如何通过忽略“\n”逐行读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16712115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How read a File line by line by ignoring "\n"
提问by Del
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.
我正在尝试每行读取一个制表符分隔的文本文件行。行通过使用回车符 ("\r\n") 分隔,并且在制表符分隔的文本字段中允许使用换行符 (\"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"?
由于我想读取每行的文件行,我希望我的程序忽略独立的“\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();
}
回答by rolfl
Use a java.util.Scanner
.
使用一个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);
}
回答by Jesper
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);
}
回答by wesoly
You can use FileUtils.readLinesmethods from apache commons-io.
您可以使用apache commons-io 中的FileUtils.readLines方法。
Advantage of using it is that you don't have to care about opening and closing file. It is handled for you.
使用它的好处是您不必关心打开和关闭文件。它为您处理。