0

好的,所以我正在制作一个程序,其中用户键入包含在 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 更改为''

4

1 回答 1

1

请参阅:在 Java 中获取当前工作目录

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

于 2013-04-08T12:32:32.273 回答