Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File not found. Why not?

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?

like image 737
William Avatar asked Nov 30 '22 07:11

William


1 Answers

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 use URL.getFile() if you really, really have to - but it's better not to.

Use getResourceAsStream instead of getResource() - that gives you an InputStream directly. Alternatively, keep using getResource() if you want the URL for something else, but then use URL.openStream() to get at the data.

like image 119
Jon Skeet Avatar answered Dec 04 '22 08:12

Jon Skeet