Avatar ·

Reading a text file in Java: a step-by-step guide for beginners

Hello everyone! I've been learning Java for about a month and came across a task that seems simple but has me stuck. I need to read a regular text file (e.g., log.txt or data.txt) and output its contents to the console. I've tried a bunch of options from the internet, but every time something goes wrong. Here's what I tried:
import java.io.*;

public class ReadFile {
    public static void main(String[] args) {
        File file = new File("data.txt");
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            System.out.println(line);
        }
        scanner.close();
    }
}
This code throws a "FileNotFoundException" error, even though the file is in the same folder as the source