URI方案不是“文件”

我得到例外:“URI方案不是文件”

我正在做的是尝试获取文件的名称,然后从servlet中将该文件(从另一台服务器)保存到我的计算机/服务器上。

我有一个名为“url”的字符串,从上面这里是我的代码:

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)); } 

导致错误的行是这样的:

 File fileFromUri = new File(fileUri); 

我添加了其余的代码,以便您可以看到我想要做的事情。

URI“scheme”是“:”之前的内容,例如“http://stackoverflow.com”中的“ http ”。

错误消息告诉您new File(fileUri)仅适用于“file:”URI(指的是当前系统上的路径名),而不是其他方案,如“http”。

基本上,“file:”URI是指定File类的路径名的另一种方法。 告诉File使用http从Web获取文件并不是一种神奇的方法。

您从URL创建File假设在这里是错误的。

您只需要从URL创建File到Internet中的文件,以便获取文件名。

您可以通过解析URL来执行此操作:

 URL fileUri = new URL("http://sofzh.miximages.com/java/fish4.jpg"); int startIndex = fileUri.toString().lastIndexOf('/'); String fileName = fileUri.toString().substring(startIndex + 1); System.out.println(fileName);