import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class FileReadSimple {

	public static void main(String[] args) {

		Scanner keyboard = new Scanner(System.in);
		
		System.out.print("Enter a filename: ");
		String filename = keyboard.nextLine();
		File file = new File(filename);
		//File file = new File("./" + filename);
		
		//present working directory
		File pwd = new File(".");
		
		try {
			System.out.printf("pwd: %s\n", pwd.getCanonicalPath());
			System.out.printf("file: %s\n", file.getCanonicalPath());
			
			//if the path doesn't start with pwd, then exit
			if(!(file.getCanonicalPath().startsWith(pwd.getCanonicalPath()))) {
				System.err.println("Unable to open file.");
				System.exit(1);
			}
		}
		catch(IOException ioe) {
			//ioe.printStackTrace();
			System.err.println("Unable to open file: " + file);
		}
		
		try (Scanner fileIn = new Scanner(file)){
			int l = 0;
			while(fileIn.hasNextLine()) {
				String line = fileIn.nextLine();
				System.out.printf("%4d: %s\n", l, line);
				l++;
			}
		}
		catch(IOException ioe) {
			//ioe.printStackTrace();
			System.err.println("File read error: " + file);
		}
		
		keyboard.close();
	}


}
