Hi,
The problem is that it doesnt know where to search the file from. Try the following.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ReadFirstLine
{
public static void main(String[] args) throws IOException
{
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the file name.
System.out.print("Enter the name of a file: ");
String filename = keyboard.nextLine();
//System.out.print(filename);
// Open the file.
File file = new File(filename);
String folder = "D:\\CP\\Test\\";
//System.out.println(folder + file.getPath());
String filepath = folder + file.getPath();
Scanner inputFile = new Scanner(new BufferedReader(new FileReader(filepath)));
// Read the first line from the file.
String line = inputFile.nextLine();
// Display the line.
System.out.println("The first line in the file is:");
System.out.println(line);
// Close the file.
inputFile.close();
}
}
Enjoy