【问题标题】:How to read file with cyrillic path如何读取带有西里尔文路径的文件
【发布时间】:2012-09-06 20:40:01
【问题描述】:

其实我还有下一个代码:

String f = LauncherFrame.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // path to launcher
java.lang.System.out.println(f);

String launcherHash = "";

try{
  MessageDigest md5  = MessageDigest.getInstance("MD5");
  launcherHash = calculateHash(md5, f);
}catch (Exception e) {
  java.lang.System.out.println(e){
  return;
}

calculateHash函数:

public static String calculateHash(MessageDigest algorithm,String fileName) throws Exception{
      FileInputStream    fis = new FileInputStream(fileName);
      BufferedInputStream bis = new BufferedInputStream(fis);
      DigestInputStream  dis = new DigestInputStream(bis, algorithm);

      while (dis.read() != -1);
            byte[] hash = algorithm.digest();

      return byteArray2Hex(hash);
}

当我的 .jar 文件在路径中没有西里尔字符时,它在 unix/windows 上运行良好。但是当它有时,我得到下一个异常:

java.io.FileNotFoundException: 
C:\Users\%d0%90%d1%80%d1%82%d1%83%d1%80\Documents\NetBeansProjects\artcraft-client\build\classes (Can't find file)

我该如何解决?

【问题讨论】:

    标签: java character-encoding filenotfoundexception


    【解决方案1】:

    这是从内存中提取的,因此语法可能有点偏差,但最好的方法可能是使用内置的 URL 支持直接从 URL 打开流;

    URL url = LauncherFrame.class.getProtectionDomain().getCodeSource().getLocation();
    

    然后将 URL 传递给 calculateHash 而不是文件名,并使用 URL's openStream method 获取包含内容的流;

    InputStream is = url.openStream();
    BufferedInputStream bis = new BufferedInputStream(is);
    ...
    

    【讨论】:

      猜你喜欢
      • 2017-09-10
      • 2013-06-02
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      相关资源
      最近更新 更多