Can't read integer file

I’m trying to read data from a file that contains integers, but the Scanner doesn’t read anything from that file.

I’ve tried to read the file from the Scanner :

// switch() blablabla 
case POPULATION:
            try {
                while (sc.hasNextInt()) {
                    this.listePops.add(sc.nextInt());
                }
            } catch (Exception e) {
                System.err.println("~ERREUR~ : " + e.getMessage());
            }
            break;

And if I try to print each sc.nextInt() to the console, it just prints a blank line and then stops.
Now when I read the same file as a String :

?652432
531345
335975
164308
141220
1094283
328278
270582
// (Rest of the data)

So I guess he can’t read the file as a list of integers since there’s a question mark at the beginning, but the problem is that this question mark doesn’t appear anywhere in my file, so I can’t remove it.
What am I supposed to do ?
Thanks in advance

>Solution :

It looks like the Scanner is not able to read the file as a list of integers because there is a question mark at the beginning of the file. This could be due to a variety of reasons, such as a hidden character at the beginning of the file, or a problem with the encoding of the file.

One thing you could try is to use a different tool to read the file, such as the BufferedReader class. This class allows you to read a file line by line as a String, and then you can parse the String into an integer using the Integer.parseInt() method. Here is an example of how you could do this:

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
    int value = Integer.parseInt(line);
    this.listePops.add(value);
}

Alternatively, you could try reading the file as a String and then using a regular expression to extract the integers from the String. You can use the following regular expression to extract all the integers from a String
You can use the find() method of the Matcher class to find all the matches in the String, and then use the group() method to extract the actual integer value. Here’s an example of how you could use this approach:

String input = "652432 531345 335975 164308 141220 1094283 328278 270582";
Matcher matcher = Pattern.compile("(\\d+)").matcher(input);
while (matcher.find()) {
    int value = Integer.parseInt(matcher.group());
    this.listePops.add(value);
}

You can also try specifying the encoding when creating the Scanner, like this:

Scanner sc = new Scanner(new FileInputStream(file), "UTF-8");

Leave a Reply