java查找文件的路径
好的,我正在制作一个程序,用户输入一个包含在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\”,因此我可以将其传递给fileOutputStream构造函数 基本上,getpath方法将“\”更改为“/”,将%20更改为“”
# 1 楼答案
请参阅:Get current working directory in Java
不需要getPath方法,因为Java提供了处理路径的方法