【问题标题】:URI scheme is not "file"URI 方案不是“文件”
【发布时间】:2011-02-20 01:49:09
【问题描述】:

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

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

【问题讨论】:

    标签: java exception servlets uri file-uri


    【解决方案1】:

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

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

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

    【讨论】:

    • 那么你如何使用 FileReader 使用 HTTP 来获取文件呢?
    【解决方案2】:

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

    您只是不需要从 URL 到 Internet 中的文件创建一个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);
    

    【讨论】:

      猜你喜欢
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 2012-05-12
      • 2011-12-13
      • 2021-08-08
      • 2012-06-14
      相关资源
      最近更新 更多