Search code examples
javafile-exists

File exists check does not work


This is my code:

String path = "/src/cst/org/main/data/data.txt";
    File f = new File( path );
    if( f.exists() ) { 
        yesorno = true;
        System.out.println( "File exists: " + yesorno );
    } else {
        yesorno = false;
        System.out.println( "File does not exist: " + yesorno );
    }

When I run this I always get "File does not exist..." even though the file exists for sure. And if I type the full path (C:/User/....) it works but I want to let it work by shorting the code.

I know this path works actually because on another class the method finds my pictures (.png). Do I have to add something because it's a .txt?


Solution

  • Yes, because you are not doning it correct, you want to give a full path to the file.
    Use :

    String path=getClass().getResource("/path/to/file").toString().replace("file:/", "");