How to open a file in Java and correctly specify its name?

My professor assigned a program that opens a file and reads its lines. He provided the following example:

import java.io.*;  
import java.util.Scanner;  

public class LineNumbers {  
    public static void main(String[] args) throws IOException {  
        Scanner keyboard = new Scanner(System.in);  

        System.out.print("Enter the filename: ");  
        String filename = keyboard.nextLine();  

        File file = new File(filename);  
        Scanner inputFile = new Scanner(file);  

        while (inputFile.hasNext()) {  
            String familyName = inputFile.nextLine();  
            System.out.println(familyName);  
        }  

        inputFile.close();  
        keyboard.close();  
    }  
}

The issue is, when I run the program and it prompts me to enter a filename, what exactly should I type? If I create a text file named "test.txt" on my desktop and enter "test.txt" into the program, it doesn’t open the file.

Am I missing a specific format or path to ensure the file is correctly found and read?

The issue likely comes from how your program locates the file.

When you enter “test.txt”, Java looks for it in the current working directory, which is typically where your program runs (e.g., your project folder, not the Desktop).

Solution 1: Provide the Full Path

Instead of just “test.txt”, try entering the absolute path:

Windows: C:\Users\YourUsername\Desktop\test.txt

Mac/Linux: /Users/YourUsername/Desktop/test.txt

For example, when prompted, type:

C:\Users\JohnDoe\Desktop\test.txt or /Users/JohnDoe/Desktop/test.txt

That’s correct! But a more flexible approach is to use file.getAbsolutePath() to check where Java is looking:

File file = new File(filename);
System.out.println("Looking for file at: " + file.getAbsolutePath());

This prints the actual path Java is expecting. If it’s not the correct location, move your file or adjust your input.

If you’re running this program from an IDE like IntelliJ or Eclipse, put test.txt in the root of your project folder.

If using the command line, place it in the same folder where you run java LineNumbers.