problem while loading resource
Hi all
I have written the following code .
public class Test {
/** Creates a new instance of Test */
public Test() {
}
private static String Resource_Uri;
public static void main(String args[])
{
Class c=Test.class;
URL u=c.getClass().getResource("test.txt");
try
{
URI uri=new URI(u.toString());
File f=new File(uri);
}
catch(Exception e)
{
}
System.out.println(u);
}
}
But in this code the function getResource() returns null . I have deployed test.txt at the same package.
Can any one suggest why this function is returning null value while there is a resource in that location .If it is something related to classLoaders and if yes how can I solve this problem.
Thanks
[827 byte] By [
ash05182a] at [2007-10-3 3:39:53]

it would only work if Test is on the default package
the getResource does not perform the search relative to the current folder (package) of the source file, but relative to the root folder of the application (default folder). so you must change it to:
URL u=c.getClass().getResource("package/test.txt");
a better solution than hardcoding the path would be like this:
URL u=c.getClass().getResource(Test.class.getPackage().getName().replace('.','/')+"/test.txt");
Hi ash,
try this
import java.net.URL;
public class Test
{
public static void main(String args[])
{
new Test().getFilePath("test.txt");
}
void getFilePath(String fileName)
{
URL u=getClass().getResource("/"+getClass().getPackage().getName().replace('.','/')+"/"+fileName);
try
{
URI uri=new URI(u.toString());
File f=new File(uri);
}
catch(Exception e)
{
}
System.out.println(u);
}
}
All I can tell you is check your classpath. Contrary to what ifschuck wrote, your call should work if test.txt is in the same directory/zip structure as Test.class--the class file not the java source. To get at something in the default package, you would use a "/" before test.txt, sort of like absolute paths in unix. As for classloaders, I don't know how this would work if you loaded Test.class via a URL, but with the default classloader this looks fine.
Looking at your code again, I see the problem. ISMAIL_SHAIK had it right. It's on the line URL u=c.getClass().getResource("test.txt");
The variable c is already a class object, specifically Test.class. This is what you should be calling getResource() with. What you have is calling getResource on Test.class.getClass(), which is java.lang.Class.class. getResource is looking for test.txt under a structure like java/lang/test.txt. Just use URL u=c.getResource("test.txt");