0

ok so I am making a program where the user types a file name that is included in the jar file, so the program extracts that file from the jar then opens it.I have no problem doing any of this, there is just something weird that I don't understand here is the code I'm using:

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;
}

my question is about the getpath method, I don't think it is necessary, I think that java has a built in method to do that getClass().getProtectionDomain().getCodeSource().getLocation().getPath())="/C:/test%20test/" it is converted to "\C:\test test\" so I can pass it to the fileOutputStream constructor basically the getpath method changes the '\' to '/' and the %20 to ' '

tshepang
  • 12,111
  • 21
  • 91
  • 136
user2249621
  • 65
  • 1
  • 5

1 Answers1

1

Please see: Get current working directory in Java

The getPath method is not needed as Java provides methods to deal with paths.

Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155
  • dude the post doesn't say how to convert the %20 to ' ' I've read it all – user2249621 Apr 08 '13 at 12:48
  • Are you running getClass().getProtectionDomain().getCodeSource().getLocation().getPath() in windows or linux? I'm getting forward slashes / when I use this. – Menelaos Apr 08 '13 at 12:50
  • I'm running it on windows, yes I'm getting forward slashes too. – user2249621 Apr 08 '13 at 12:57
  • Ok never mind I've found the solution here http://stackoverflow.com/questions/6164448/convert-url-to-normal-windows-filename-java thanks for your concern :) – user2249621 Apr 08 '13 at 13:01