URI scheme is not "file"

Ankur picture Ankur · May 16, 2010 · Viewed 38.6k times · Source

I get the exception: "URI scheme is not file"

What I am doing is trying to get the name of a file and then save that file (from another server) onto my computer/server from within a servlet.

I have a String called "url", from thereon here is my code:

url = Streams.asString(stream); //gets the URL from a form on a webpage
System.out.println("This is the URL: "+url);
URI fileUri = new URI(url);

File fileFromUri = new File(fileUri);                   

onlyFile = fileFromUri.getName(); 
URL fileUrl = new URL(url);
InputStream imageStream = fileUrl.openStream();
String fileLoc2 = getServletContext().getRealPath("pics/"+onlyFile);

File newFolder = new File(getServletContext().getRealPath("pics"));
    if(!newFolder.exists()){
        newFolder.mkdir();
    }
    IOUtils.copy(imageStream, new FileOutputStream("pics/"+onlyFile));
} 

The line causing the error is this one:

File fileFromUri = new File(fileUri);                   

I have added the rest of the code so you can see what I am trying to do.

Answer

David Gelhar picture David Gelhar · May 16, 2010

The URI "scheme" is the thing that comes before the ":", for example "http" in "http://stackoverflow.com".

The error message is telling you that new File(fileUri) works only on "file:" URI's (ones referring to a pathname on the current system), not other schemes like "http".

Basically, the "file:" URI is another way of specifying a pathname to the File class. It is not a magic way of telling File to use http to fetch a file from the web.