views:

505

answers:

3

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?

+4  A: 

FileInputStream takes a file name as parameter, not a URL string.

The usual way to get at the contents that a URL points to is with openStream. You can open a stream to a resource without touching a URL yourself with Class/ClassLoader.getResourceAsStream (it opens the URL within the implementation).

Alternatively, you can open file URLs with:

InputStream in = FileInputStream(new File(url.toURI()));

For a resource this would require that you have raw class files outside of a jar on your filesystem. JNLP (Java WebStart) has an API for opening files is a safe manner.

In general: When converting to a String use toString or String.valueOf to be clear about what you are doing. Also note that String is somewhat weakly typed, in that the type gives no indication as to the format of the data it contains, so favour the likes of URI or File.

Tom Hawtin - tackline
So how can I properly load a file than? This is going into a Java Web Start Jar.
William
+13  A: 

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.

Jon Skeet
What was the reason the first throws FnFE end the second don't?
OscarRyz
The second uses ImageIO.read() which takes a URL.
Jon Skeet
A: 

Try seeing if the file you are trying to access is being found or the intended file. Use Sys internals File Monitor. It helps monitoring which files were being accessed by the SO.

Edison Gustavo Muenz