Java URI 方案不是“文件”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2843557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:31:51  来源:igfitidea点击:

URI scheme is not "file"

javaexceptionservletsurifile-uri

提问by Ankur

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

我收到异常:“URI 方案不是文件”

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.

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

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

我有一个名为“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));
} 

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.

我已经添加了其余的代码,所以你可以看到我想要做什么。

采纳答案by David Gelhar

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

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

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".

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

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

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

回答by Leni Kirilov

Your assumption to create Filefrom URLis wrong here.

你的假设,建立FileURL是错在这里。

You just don't need to create a Filefrom URL to the file in the Internet, so that you get the file name.

你只是不需要创建一个File从 URL 到 Internet 中的文件,这样你就可以得到文件名。

You can simply do this with parsing the URL like that:

你可以简单地通过解析 URL 来做到这一点:

URL fileUri = new URL("http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/domefisheye/ladybug/fish4.jpg");    
int startIndex = fileUri.toString().lastIndexOf('/');
String fileName = fileUri.toString().substring(startIndex + 1);
System.out.println(fileName);