I am trying to load a file called Test from my class, but somehow Java says, that the file does not exist, while it clearly does and neither the URL object url is null nor does it contain an invalid path and when I debug the program, the File object file has the right path stored in it. When I print out file.getPath() and paste it into the Windows Explorer it opens up just fine. I am running Eclipse, but I tried running the program in a console and it doesn't work either.
public static void main(String[] args) { URL url = Test.class.getResource("/Test"); File file = new File(url.toExternalForm()); if (!file .exists()) { System.out.println("File does not exist: " + file.getPath()); System.exit(-1); } } I tried it with getResource("Test"), File("Test") and File("/Test") as well, but that didn't work either. I don't know why this happens know, since I work often with files and never had a problem.
The file I want to load is located in a source folder and yes, I checked, it is recognized as a source folder in Eclipse and is in the classpath. By the way the file is actually just called Test without an extension.
Bin folder:
bin/ |___package/Test.class |___Test Output (Project is called "Other"):
File does not exist: file:\F:\Development\CoolDirectory\Other\bin\Test
url.toExternalForm()instead ofurl.getFile()getResource(..)is one way, but a very complicated and error prone. If you want read the filegetResourceAsStream(..)is the better alternative.getResourceis afile:; that sounds like a bad idea. If the resource doesn't exist,getResourcewill return null. Couldn't you useurl.openStream()to read the file?!file.exists()instead of!file. exists()- there shouldn't be a space.