Search code examples
javajava.util.scannerfilenamesbufferedreader

Java Scanner(System.in) does not open file after user input


Hello there I am facing an issue which I cannot find a solution. I am asking the user to input the name of a file but the output i get is always ''unable to open file''. Any advice would be much appreciated.

    Scanner reader = new Scanner(System.in); 
    System.out.println("Enter the name of textfile to be read ( add .txt): ");

    String fileName = reader.next();
    String line = null;
    BufferedReader bufferedReader =   new BufferedReader(fileReader);

    while((line = bufferedReader.readLine()) != null) {
        System.out.println(line); 

        catch(FileNotFoundException ex) {
        System.out.println(
            "Unable to open file '" + 
            fileName + "'");                
       }

        catch(IOException ex) {
        System.out.println(
            "Error reading file '" 
            + fileName + "'");                  
        // Or we could just do this: 
        // ex.printStackTrace();
    }
    }

The FileNotFoundException is always executed but why?

P.S if I change the path to a specific location such as "C:\etc" it reads the file.


Solution

  • If you don't specify the absolute file path, ie, C:/dir/..., java will look in the same directory as the project root (the same directory as your src and bin folders). If the file is there, it will find it with just the file name, or if you make a directory in that folder, you would need that directory in the path. The same is true if you have an executable JAR, it will look in the same directory that the JAR is located.