Okay, I’m trying to load a file in Java using this code:
String file = 'map.mp'; URL url = this.getClass().getResource(file); System.out.println('url = ' + url); FileInputStream x = new FileInputStream('' + url);
and despite the file being in the same folder as the class it says it can’t find it (yes, it is in a try catch block in the full code).
However, it finds another file using the same code with a different name:
URL url = this.getClass().getResource('default.png'); System.out.println('url2 = ' + this.getClass().getResource('default.png')); BufferedImage img = ImageIO.read(url);
Why can’t my code find my map.mp file?
You’re trying to use a url as if it’s a filename. It won’t be. It’ll be something starting with
file://. In other deployment scenarios there may not be an actual file to open at all – it may be within a jar file, for example. You can useURL.getFile()if you really, really have to – but it’s better not to.Use
getResourceAsStreaminstead ofgetResource()– that gives you anInputStreamdirectly. Alternatively, keep usinggetResource()if you want the URL for something else, but then useURL.openStream()to get at the data.