I have a project named Downloader containing files like this:
Downloader
-->src
-->Downloader
-->DownLoader.java
-->AudioLinks
I have tried to access AudioLinks from Downloader.java by the following function.
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");
}
}
}
It returned the following:
E:\Project%20Eclipse\Workspace\Downloader\bin\Downloader\AudioLinks Doesn't exist
But if I edit the function like this(replace "%20" by a " "):
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");
}
}
}
It returns:
E:\Project Eclipse\Workspace\Downloader\bin\Downloader\AudioLinks Exists
The problem is that if I export my program to runnable jar it gives "Doesn't exist" in both cases. Could anyone please explain these occurances?
peeskillet wrote in his comment: Don't read it as a File. Read it as a URL through just the getResource(). Get rid of the File wrapper (or an an InputStream through getResourceAsStream, depending on the type required)
So, I've edited the function like this and found no error:
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();
}
}
}