17

我得到了例外:“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);                   

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

4

2 回答 2

30

URI“方案”是出现在“:”之前的东西,例如“http://stackoverflow.com”中的“ http ”。

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

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

于 2010-05-16T11:43:20.627 回答
5

您在这里创建的假设FileURL错误的。

您只是不需要File在 Internet 上创建一个指向该文件的来自 URL,这样您就可以获得文件名。

你可以简单地通过解析 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);
于 2010-05-16T12:40:46.667 回答