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);
我已经添加了其余的代码,以便您可以看到我正在尝试执行的操作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
URI“scheme”是“:”之前的内容,例如“http://stackoverflow.com”中的“http”。
错误消息告诉您
new File(fileUri)
仅适用于“file:”URI(引用当前系统上的路径名),而不适用于“http”等其他方案。基本上,“file:”URI 是指定
File
类路径名的另一种方式。这并不是告诉File
使用 http 从网络获取文件的神奇方法。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 tellingFile
to use http to fetch a file from the web.您从
URL
创建File
的假设在这里是错误的。您只是不需要从 Internet 上的文件的 URL 创建一个
File
来获取文件名。您可以简单地通过解析 URL 来完成此操作,如下所示:
Your assumption to create
File
fromURL
is wrong here.You just don't need to create a
File
from URL to the file in the Internet, so that you get the file name.You can simply do this with parsing the URL like that: