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);
}
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.
来源:https://stackoverflow.com/questions/16712115/java-how-read-a-file-line-by-line-by-ignoring-n