javafilelinefile-handlingend-of-line

Detect the end of line in file


I am trying to read a txt file and display the file elements. I want to display elements in same line to give a single line break. But, give extra new line when new line in file starts. The txt file is:

Interstellar % Christopher Nolan % 2014 % PG-13

Inception % Christopher Nolan % 2010 % PG-13

Endgame % Russo Brothers % 2019 % PG-13

Here, % is delimeter. What I have done so far:

File file_path = new File("film.txt");
try {
    Scanner file_input = new Scanner(file_path);
    file_input.useDelimiter("%");
    for(new_book=1; file_input.hasNext(); new_book++) {
        String book_item = file_input.next().trim();
        System.out.println(book_item);
        if(new_book%4==0){
            System.out.println();
        }
    }
    file_input.close();
} 
catch (FileNotFoundException e) {
    System.out.println("File not found");
}

What it gives:

Interstellar 
Christopher Nolan
2014
PG-13
Inception 

Christopher Nolan
2010
PG-13
Endgame 
Russo Brothers

2019 
PG-13

What I want is:

Interstellar 
Christopher Nolan
2014
PG-13

Inception 
Christopher Nolan
2010
PG-13

What I have noticed is, at the end of line indexing is not working i.e, if I print new_book then, new_book value is not shown in first and second PG-13, but shows in last PG-13.

I am confused with this line in file. Every suggestion is appreciated!!! Also, note that I am not confuse with syntactical error. But, with the logic and how file reading process is done.


Solution

  • The problem is that the line break is not considered as a delimiter so the 4th token is read as PG-13<NEWLINE>Inception - with a line break embedded inside. Your options are:

    Add line break as a possible delimiter:

    Scanner file_input = new Scanner(file_path);
    file_input.useDelimiter("%|\n");
    

    Or add % at the end of every line in the input file:

    Interstellar % Christopher Nolan % 2014 % PG-13 %
    Inception % Christopher Nolan % 2010 % PG-13 %

    Or change the way the file is read to reading line by line and splitting on % (see answers by others)