javaeclipsejava.util.scannerresource-leak

Resource leak not closed


I'm using Eclipse, and doing the function below, it happens that I'm opening a Scanner, and then, in the end I close it, but Eclipse keeps saying that it is not closed "resource leak: 'scanner' is not closed". I can do it with try with resources, and the warning disappears, but I want to understand why the way I'm trying in here doesn't work

   private void follow(String userID) {

        if(!(new File("../users/"+userID+"/")).exists()){
            System.out.println("User especificado nao existe");
            return;
        }

        File list = new File("../users/"+userID+"/followers.txt");
        try {
            list.createNewFile();

            Scanner scanner = new Scanner(list);
            while(scanner.hasNextLine()){
                String line = scanner.nextLine();
                if(line.equals(clientID)){
                    System.out.println("Cliente ja segue este user");
                    return;
                }
            }

            PrintWriter out = new PrintWriter(new FileWriter(list, true));
            out.append(clientID+"\n");

            out.close();
            scanner.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Solution

  • #createNewFile() can throw an IOException before you get to the close() statement, keeping it from being executed.