在文件名中检索到带有变音符号的URL时,将返回java.io.FileNotFoundException [英] java.io.FileNotFoundException when retrieving a url with umlauts in the filename

查看:125
本文介绍了在文件名中检索到带有变音符号的URL时,将返回java.io.FileNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在文件名中检索一个带有变音符的URL,像http://somesimpledomain.com/some/path/überfile.txt,但它给了我一个java.io.FileNotFoundException。我怀疑远程服务器上的文件名编码在latin1中,尽管我的url在utf8中。但是我尝试更改URL的编码不成功,我不知道如何进一步调试。请帮助!



代码如下:

  HttpURLConnection conn =空值; 
try {
conn =(HttpURLConnection)new URL(uri).openConnection();
conn.setRequestMethod(GET);
} catch(MalformedURLException ex){}
} catch(IOException ex){}

//过滤头
int i = 1;
String hKey;
while((hKey = conn.getHeaderFieldKey(i))!= null){
conn.getHeaderField(i);
i ++;
}

//打开文件并输出流
InputStream in = null;
OutputStream out = null;
尝试{
in = conn.getInputStream();
} catch(IOException ex){
ex.printStackTrace();
}

try {
out = response.getOutputStream();
} catch(IOException ex){
}

问候,
Hendrik

解决方案

URL需要正确编码。你必须知道您的服务器期望的字符集/编码。你可以先尝试一下,

  String uri =http://somesimpledomain.com/some/path/+ 
URLEncoder.encode(filename,ISO-8859-1);

如果不行,请将ISO-8859-1替换为UTF-8然后再试一次。



如果还不行,文件不存在:)


I am trying to retrieve a url with an umlaut in the filename, something like "http://somesimpledomain.com/some/path/überfile.txt", but it gives me a java.io.FileNotFoundException. I suspect that the filename on the remote server is encoded in latin1, though my url is in utf8. But my tries to change the encoding of the url weren't successful and I don't know how to debug it further. Please help!

Code is as follows:

   HttpURLConnection conn = null;
    try {
       conn = (HttpURLConnection) new URL(uri).openConnection();
       conn.setRequestMethod("GET");
    } catch (MalformedURLException ex) {}
    } catch (IOException ex){}

    // Filter headers
    int i=1;
    String hKey;
    while ((hKey = conn.getHeaderFieldKey(i)) != null) {
        conn.getHeaderField(i);
        i++;
    }

    // Open the file and output streams
    InputStream in = null;
    OutputStream out = null;
    try {
        in = conn.getInputStream();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    try {
        out = response.getOutputStream();
    } catch (IOException ex) {
}

Regards, Hendrik

解决方案

URL needs to be properly encoded. You have to know what charset/encoding your server is expecting. You can try this first,

 String uri = "http://somesimpledomain.com/some/path/" + 
     URLEncoder.encode(filename, "ISO-8859-1");

If that doesn't work, replace "ISO-8859-1" with "UTF-8" and try again.

If that doesn't work either, file doesn't exist :)

这篇关于在文件名中检索到带有变音符号的URL时,将返回java.io.FileNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆