【问题标题】:Finding path of a file [closed]查找文件的路径[关闭]
【发布时间】:2013-03-30 12:27:21
【问题描述】:

好的,所以我正在制作一个程序,其中用户键入包含在 jar 文件中的文件名,因此程序从 jar 中提取该文件然后打开它。我做这些都没有问题,只有我在这里不明白的奇怪之处是我正在使用的代码:

String path=getpath(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
public void open(String filename) throws FileNotFoundException, IOException{
    InputStream is = getClass().getResourceAsStream("pdfs/"+filename);
    OutputStream os = new FileOutputStream(path+"SultanKadab.pdf");
    byte[] buffer = new byte[4096];
    int length;
    while ((length = is.read(buffer)) > 0)
        os.write(buffer, 0, length);
    os.close();
    is.close();
if (pdfFile.exists()&&Desktop.isDesktopSupported())
         Desktop.getDesktop().open(pdfFile); //opening file
}

public String getpath(String f){
    String s = "";
    int lastInd=0;
    for(int i=0;i<f.length();i++){
        if(f.charAt(i)=='/'){s+="\\";lastInd=s.length()-1;}
        else if(f.charAt(i)=='%'&&f.length()-i>=2){
            if(f.charAt(i+1)=='2'&&f.charAt(i+2)=='0')i+=2;s+=" ";
        }
        else s+=f.charAt(i);
    }
    f=s.substring(0,lastInd+1);
    return f;
}

我的问题是关于 getpath 方法,我认为没有必要,我认为 java 有一个内置方法可以做到这一点 getClass().getProtectionDomain().getCodeSource().getLocation().getPath())="/C:/test%20test/" 它被转换为“\C:\test test\”,所以我可以将它传递给 fileOutputStream 构造函数 基本上 getpath 方法将 '\' 更改为 '/' 并将 %20 更改为 ' '

【问题讨论】:

  • 我认为您不必进行这种转换。 Java 应该可以很好地处理您获得的路径。

标签: java file path space


【解决方案1】:

请看:Get current working directory in Java

不需要getPath方法,因为Java提供了处理路径的方法。

【讨论】:

  • 老兄帖子没有说明如何将 %20 转换为 ' ' 我已经阅读了所有内容
  • 你是在windows还是linux中运行getClass().getProtectionDomain().getCodeSource().getLocation().getPath()?当我使用这个时,我得到了正斜杠/。
  • 我在 Windows 上运行它,是的,我也在使用正斜杠。
  • 好吧,没关系,我在这里找到了解决方案stackoverflow.com/questions/6164448/…,感谢您的关注:)
猜你喜欢
  • 2012-02-25
  • 2020-11-03
  • 1970-01-01
  • 2012-04-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多