0

This is my file directory

enter image description here

I am trying to open admin.dat for reading but dont understand why am i unable to open the file and the FileNotFound exception is always thrown

Code:

public void readfile(){
    try{
        Scanner filereader = new Scanner(new File("admin.dat"));
        String data;

        while(filereader.hasNextLine()){
            data = filereader.nextLine();
            System.out.println(data);
        }
    }
    catch (FileNotFoundException e){
        System.out.println("File not found");
    }
    catch (IOException e){
        System.out.println("Error while reading file");
    }
}
Computernerd
  • 7,378
  • 18
  • 66
  • 95
  • You have to specify the path starting from the directory where the `src` and `build` directories are. So `src/javaassignment1/admin.dat` – BackSlash Apr 01 '14 at 17:11
  • Try putting admin.dat in the equivalent location to where the class files are, this is probably a directory called bin. – NESPowerGlove Apr 01 '14 at 17:12

1 Answers1

2

Generally when you launch app through IDE they set current directory to the root of the project so you need to pass relative path from there

You can check what is set as current directory by

System.out.println(System.getProperty("user.dir"));

ALso it will just work as long as the file exists as a real File, if you bundle it in jar or some other form of archive it will stop working, so better to read it as Resource from classpath

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438