Java 查找文件的路径
好的,我正在制作一个程序,其中用户键入一个包含在jar文件中的文件名,程序从jar中提取该文件,然后打开它。我做这些都没有问题,只是有些奇怪的事情我不明白,下面是我使用的代码:Java 查找文件的路径,java,file,path,space,Java,File,Path,Space,好的,我正在制作一个程序,其中用户键入一个包含在jar文件中的文件名,程序从jar中提取该文件,然后打开它。我做这些都没有问题,只是有些奇怪的事情我不明白,下面是我使用的代码: String path=getpath(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); public void open(String filename) throws FileNotFoundException, IO
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;
}
String path=getpath(getClass().getProtectionDomain().getCodeSource().getLocation().getpath());
公共void open(字符串文件名)引发FileNotFoundException、IOException{
InputStream=getClass().getResourceAsStream(“PDF/”+文件名);
OutputStream os=新文件OutputStream(路径+“SultanKadab.pdf”);
字节[]缓冲区=新字节[4096];
整数长度;
而((长度=is.read(缓冲区))>0)
写操作(缓冲区,0,长度);
os.close();
is.close();
if(pdfFile.exists()&&Desktop.isDesktopSupported())
Desktop.getDesktop().open(pdfFile);//打开文件
}
公共字符串getpath(字符串f){
字符串s=“”;
int lastInd=0;
对于(int i=0;i=2){
如果(f.charAt(i+1)='2'&&f.charAt(i+2)='0')i+=2;s+=“”;
}
否则s+=f.charAt(i);
}
f=s.子串(0,lastInd+1);
返回f;
}
我的问题是关于getpath方法的,我认为没有必要,我认为java有一个内置的方法来实现这一点
getClass().getProtectionDomain().getCodeSource().getLocation().getPath())=“/C:/test%20test/”
它被转换为“\C:\test\”,因此我可以将其传递给fileOutputStream构造函数
基本上,getpath方法将“\”更改为“/”,将%20更改为“”请参见:
不需要getPath方法,因为Java提供了处理路径的方法。我认为您不必进行这种转换。Java应该可以很好地处理您获得的路径。dude这篇文章没有说如何将%20转换为“”,我已经读过了。您在windows或linux中运行getClass().getProtectionDomain().getCodeSource().getLocation().getPath()吗?我正在使用前斜杠/当我使用它时。我正在windows上运行它,是的,我也正在使用前斜杠。好的,没关系,我在这里找到了解决方案,谢谢您的关注:)