File not found. Why not?

Ok, I'm trying to upload 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 fact that the file is in the same folder as the class, it says that it cannot find it (yes, it in the 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
source share
4 answers

You are trying to use the url as if it is a file name. It will not happen. This will be something starting with file:// . In other deployment scenarios, there may not be an actual file to open at all — it could be, for example, in a jar file. You can use URL.getFile() if you really need to - but it's best not to.

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

+18
source

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

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

Alternatively, you can open the file with:

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

For a resource, this will require that you have the source class files outside of the jar in your file system. JNLP (Java WebStart) has an API for opening files, this is a safe way.

In general: when converting to String use toString or String.valueOf to understand what you are doing. Also note that String somewhat weakly typed, since the type gives no indication of the format of the data contained in it, so prefer a URI or a File .

+4
source

Try to see if the file you are trying to access or the file is found. Use Internal Sys File Monitor . It helps control what files SO accessed.

0
source

Do you have a place in your way? Do you see% 20? Remove it. Then it will work: getResource (file), as getResourceAsStream () does.

Spaces are evil along the paths. Always avoid them.

0
source

All Articles