Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How read a File line by line by ignoring "\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.

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();
}
like image 748
Del Avatar asked May 23 '13 10:05

Del


People also ask

How read data from line from file in Java?

Java Read File line by line using BufferedReader We can use java. io. BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached.

How do you stop a line break in Java?

Line Break: A line break (“\n”) is a single character that defines the line change. In order to replace all line breaks from strings replace() function can be used.

Does Java readLine include newline?

In Java, readLine() uses \n and \r as line feed and carriage return end characters to determine the next lines. So, when you use readLine() , then you won't get \n or \r characters to be displayed in the console as these characters will be masked by the readLine() .

Does Java read line by line?

Using the Java BufferedRedaer class is the most common and simple way to read a file line by line in Java. It belongs to java.io package. Java BufferedReader class provides readLine() method to read a file line by line.


1 Answers

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);
}
like image 139
rolfl Avatar answered Sep 22 '22 21:09

rolfl