my professor wants us to write a program that will open a file and read the lines and he gave this example;
import java.io.*;
import java.util.Scanner;
import java.io.IOException;
public class LineNumbers {
public static void main(String[] args) throws IOException { // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get the filename. System.out.print("Enter the filename: "); String filename = keyboard.nextLine(); // Open the file. File file = new File(filename); Scanner inputFile = new Scanner(file); // Read lines from the file until no more are left. while (inputFile.hasNext()) { // Read the next name. String familyName = inputFile.nextLine(); // Display the last name read. System.out.println(familyName); } // Close the file. inputFile.close(); keyboard.close();
}
}The problem is, once I run the program and it tells me to enter the filename, what exactly do I type? If I make a random text file named "test" on my desktop and input "test" into the program it won't open it up. Am I supposed to type some special character to open it up and have it read? Thank you.
4 Answers
Enter the full path to the file.
If you are using windows, you can get this by holding Shift and then pressing Right-Click on the file, and then selecting Copy as path.
1You can enter the file name with the whole path:
C:\\Path\\To\\The\\File.txt
or
/tmp/path/to/file.txt
Or type in just the file name given that it is located under the same path than the executable java class.
You may need to put the filename between quotes or double quotes if the path contains any spaces.
you should type the path to the file...if you are using windows, you should type something like
c:\\<path_to_desktop>\\test.txt (if it is a txt file)on linux, you should type something like
/<path_to_desktop>/test.txt 2 Try creating a sample file called "test.txt" Input some values into it such as "Hello World" Close the file
NOTE -> Make sure that the file is created in the same directory where your java program is
Now, run the java program, when the program prompts for the file name, enter text.txt (the complete name of the file)
This should run and print the contents of the file on the console, which is what this program is doing.