0

Can someone explain to me, why we need to write 'line.indexOf('#') == 0' in this code? I'm trying to load data from a text file and create objects.

         Path path = Paths.get(getClass().getClassLoader().getResource("filmovi.txt").toURI());
         //path is content of filmovi.txt
         List<String> lines = Files.readAllLines(path, Charset.forName("UTF-8"));
         //I put that content in List

        for (String line : lines) {
            line = line.trim();                                 

            if (line.equals("") || line.indexOf('#') == 0)  //why we check '#'  
                continue;
            String[] tokens = line.split(";");
            Long id = Long.parseLong(tokens[0]);
            String naziv = tokens[1];
            int trajanje  = Integer.parseInt(tokens[2]);

            filmovi.put(Long.parseLong(tokens[0]), new Film(id, naziv, trajanje));
            if(nextId<id)
                nextId=id;

This is the content of the file I am trying to load. I just don't understand why is this ('line.indexOf('#') == 0') important to check?

1;The Shining;146
2;One Flew Over the Cuckoo's Nest;133
3;The Little Shop of Horrors;72
4
  • 6
    Presumably it allows for comments in the form of # comment. By no means is it necessary, but it is helpful for hand-written files. Commented Sep 20, 2023 at 17:46
  • Yes, ignoring comments as @SuperStormer said. You need to make a decision on whether you're reading resources or arbitrarily-located files though, as the two means do not mix well Commented Sep 20, 2023 at 17:52
  • 3
    It's your code so it's up to you. If you don't want to skip lines that begin with # or don't expect lines like this in your input, you don't have to do this. Commented Sep 20, 2023 at 18:03
  • 1
    Its probably for commenting out lines, you can disallow for it, but if there exists somewhere files with commented out lines then you will get in trouble as your code might fail to load them. Commented Sep 20, 2023 at 18:27

2 Answers 2

2

In the for loop, we are checking for line.indexOf('#') == 0 to check if the line is a comment. So that the line will be ignored.

You can also use line.charAt(0) == '#' to check for comments, both ways are correct.

Commented the code for better explanation of each statement:

// getting the complete path of 'filmovi.txt' file as Path's object
Path path = Paths.get(getClass().getClassLoader().getResource("filmovi.txt").toURI());
         
// getting all lines of the file as a List
List<String> lines = Files.readAllLines(path, Charset.forName("UTF-8"));

// iterating over each line in the List of lines
for (String line : lines) {
            
        // removing extra spaces from beginning & end of each line
        line = line.trim();                                 

        // if the line is empty (means it has no characters) or line's first character is '#' (means it is a comment)
        if (line.equals("") || line.indexOf('#') == 0)
 
                // then skipping further statements of the loop, & continuing for next line
                continue;

        // splitting the line by delimiter ';' & storing splitter parts into the array of String
        String[] tokens = line.split(";");
       
        // storing the line number (which is written in starting of each line) in a Long type variable
        Long id = Long.parseLong(tokens[0]);
     
        // storing the main text of the line in a String type variable
        String naziv = tokens[1];
  
        // storing the number written at the end of each line in int type variable
        int trajanje  = Integer.parseInt(tokens[2]);

        ...
}
Sign up to request clarification or add additional context in comments.

Comments

-1

If you're going to treat the input as a resource, you could do it like this:

import java.util.Map;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class FilmParser {
    public static void main(String[] args) throws Exception {
        Map<Long, List<Film>> filmMap = null;
        try (Scanner sc = new Scanner(FilmParser.class.getResourceAsStream("/films.csv"), "UTF-8").useDelimiter("\\R")) {
            filmMap = sc.tokens()
                .map(String::trim)
                .filter(s ->!s.startsWith("#"))
                .filter(s ->!s.isEmpty())
                .map(Film::valueOfColonSV)
                .collect(Collectors.groupingBy(Film::getId));
        }
        System.out.println(filmMap);
    }
}

I've given the Film class a convenience method to create an instance from CSV

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.