Re: Java file access
1-crm@freenet.de wrote:
But then - why is it so important to access resources
*both* ways from within the one project?
Either this project will be run from loose class files
(extremely not recommended) or Jar files. It is not
difficult to generate a Jar file for use during testing.
Sorry but that not question. I was asking for a solution for both.
It's not difficult to make a solution which works for both without code changes
(see below). I presume that your difficulties are purely to do with Eclipse
and whatever magic it is performing. I can't help with that except to suggest
that you (temporarily) ditch Eclipse and work with the command line tools until
you are sure that your code is doing what you think it should do, and that it
works correctly. /Then/ you can look for the problem in Eclipse.
Anyway, this works for me (on Windows)
Code:
===================
package aaa.bbb;
public class Test
{
public static void
main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("resources/test.txt"));
}
}
===================
Note that I'm looking for the resource file using a path relative to the root
of the classpath segment (jar or directory).
Now.
File structure:
C:\Home\tmp\find-resource\aaa\bbb\Test.class
C:\Home\tmp\find-resource\resources\test.txt
Running:
java -cp C:\Home\tmp\find-resource aaa.bbb.Test
Produces:
file:/C:/Home/tmp/find-resource/resources/test.txt
Then jar-ing up to produce test.jar with contents including:
aaa/bbb/Test.class
resources/test.txt
Running:
java -cp test.jar aaa.bbb.Test
Produces:
jar:file:/C:/Home/tmp/find-resource/test.jar!/resources/test.txt
So it all works. I suggest you start with some such simple program as the
above, get it working using the command line tools, and then work out how to
make it work under Eclipse. Then apply your new-found mastery of Eclipse to
solving your original problem.
-- chris