我有一个名为 Downloader 的项目,其中包含如下文件:
Downloader
-->src
-->Downloader
-->DownLoader.java
-->AudioLinks
我尝试通过以下函数从 Downloader.java 访问 AudioLinks。
public void readFile()
{
{
File file=new File(this.getClass().getResource("AudioLinks").getFile());
if(file.exists())
{
System.out.println(file+" Exists");
}
else
{
System.out.println(file+" Doesn't exist");
}
}
}
它返回以下内容:
E:\Project%20Eclipse\Workspace\Downloader\bin\Downloader\AudioLinks Doesn't exist
但是如果我像这样编辑函数(将“%20”替换为“”):
public void readFile()
{
{
File file=new File(this.getClass().getResource("AudioLinks").getFile().replaceAll("%20", " "));
if(file.exists())
{
System.out.println(file+" Exists");
}
else
{
System.out.println(file+" Doesn't exist");
}
}
}
它返回:
E:\Project Eclipse\Workspace\Downloader\bin\Downloader\AudioLinks Exists
问题是,如果我将程序导出到可运行的 jar,则在两种情况下都会给出“不存在”。谁能解释一下这些现象吗?
最佳答案
peeskillet 在他的评论中写道: 不要将其作为文件读取。仅通过 getResource() 将其读取为 URL。摆脱文件包装器(或通过 getResourceAsStream 的输入流,具体取决于所需的类型)
所以,我像这样编辑了函数,没有发现错误:
public void readFile()
{
{
BufferedReader reader=new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("AudioLinks")));
String text;
try {
while((text=reader.readLine())!=null)
{
System.out.println(text);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
关于java - 在 java 中使用 getResource() 读取路径名中包含空格的文件时出现尴尬的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26759638/