URI方案不是“file”

19

我遇到了异常:"URI方案不是file"

我正在尝试获取文件名,并从另一台服务器上将该文件保存到我的计算机/服务器中,在一个servlet中实现。

我有一个名为"url"的String变量,以下是我的代码:

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

我已经添加了其余的代码,这样你就可以看到我在尝试做什么。

2个回答

34

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

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

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


1
那么,您如何使用FileReader通过HTTP获取文件呢? - 0xTomato

5

在这里,您创建File时的假设是错误的。

您根本不需要从Internet中的URL创建File,以获取文件名。

您只需解析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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接