Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (483)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (550)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  class.getResource() always return null  (Read 6418 times)
0 Members and 1 Guest are viewing this topic.
Offline Captain Awesome

Junior Member


Medals: 2


Hi


« Posted 2010-11-16 22:48:55 »

What I'm trying to do is to create a runnable .jar file from java. What I do is I fill the .jar file with resources, then I copy my .class files and the manifest file from another .jar file.
However, when I start the newly created .jar file, it starts up as normal. However, all calls to MyClass.class.getResource() always return null.
I have opened the .jar file with winrar and confirmed that the resources exist (they do indeed exist).

So my problem is basically that MyClass.class.getResource() can't find any resources even though they exist.

Here is the code I use to create the .jar file.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
//This function build to the project to the specified file
   public void buildProject(File file) {
        if (file == null)return;

        try {
            JarOutputStream out = new JarOutputStream(new FileOutputStream(file), new JarFile(GenericMethods.getHome()).getManifest());

            //First copy all src-files
           insert(new File("src/"), out);

            //Now copy the class files from this jar
           File jarfile = new File(GenericMethods.getHome());
            if(!jarfile.isDirectory()) insertFromJAR(out, jarfile);

            out.close();
           
        } catch (IOException ex) {
            Logger.getLogger(ProjectBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    //@input File f is the file that will be inserted
   //@input JarOutputStream out is the ouputstream connected to a jar file.
   public void insert(File f, JarOutputStream out) {
        if(f.isDirectory()) {
            File[] files = f.listFiles();
            for(File file:files)insert(file, out);
        }else {
            byte[] buf = new byte[1024];
            try {
                InputStream in = new BufferedInputStream(new FileInputStream(f));

                String path = f.getPath();
                if(path.startsWith("src"))path = path.replaceFirst("src", "").substring(1);
                out.putNextEntry(new JarEntry(path));

                int len;
                while((len=in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                out.closeEntry();
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(ProjectBuilder.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void insertFromJAR(JarOutputStream out, File jarFile) {
        try {
            JarFile jf = new JarFile(jarFile);
           
            //Get the enumerations from the zipfile
           Enumeration enums = jf.entries();

            byte[] buf = new byte[1024];

            //Loop until the enumeration has no more elements
           while(enums.hasMoreElements()) {

                //Get the next entry
               JarEntry entry = (JarEntry) enums.nextElement();

                //Check if the entryname starts with the folder name
               if(entry.getName().startsWith("Game")) {
                    InputStream in = jf.getInputStream(entry);

                    String path = entry.getName();
                    out.putNextEntry(new JarEntry(path));

                    int len;
                    while((len=in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }

                    out.closeEntry();
                    in.close();
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(ProjectBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
Offline CyanPrime
« Reply #1 - Posted 2010-11-16 23:29:56 »

I'm not even seeing getResource in that class.
system out print the path getResource gives you.
Offline Captain Awesome

Junior Member


Medals: 2


Hi


« Reply #2 - Posted 2010-11-17 11:41:35 »

I'm not even seeing getResource in that class.
system out print the path getResource gives you.

I'm using the following to get the resource:
1  
Main.class.getResource("/System/entities.xml")


That however returns null. Here is a screenshot that shows that entities.xml does exist.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 781
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #3 - Posted 2010-11-17 11:52:49 »

Drop the first slash.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline Captain Awesome

Junior Member


Medals: 2


Hi


« Reply #4 - Posted 2010-11-17 12:27:01 »

Drop the first slash.

Didn't work  Sad

Guess I have to write my own classloader to force java to find my resources  Tongue
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 781
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #5 - Posted 2010-11-17 12:29:29 »

Didn't work  Sad

Guess I have to write my own classloader to force java to find my resources  Tongue

The following is known to work, always, everywhere:
1  
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("System/entities.xml");


If it doesn't work, you might not have the JAR in your classpath.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline Abuse

JGO Knight


Medals: 12


falling into the abyss of reality


« Reply #6 - Posted 2010-11-17 12:55:10 »

Have a read of the javadoc; it explains how the path is resolved.

To summarize:

If the resource name begins with '/', then the path is absolute - taken from the root of the class path. (i.e. it will find resources that reside in what would be otherwise called the default package)
Otherwise, the resource is relative to the package folder of the Class you are invoking the method upon.

So:

1  
somePackage.SomeClass.class.getResourceAsStream("data/some.file");


will give the same results as:

1  
AnyClass.class.getResourceAsStream("/somePackage/data/some.file");


I'm not sure why your initial example doesn't work; you might need to show a little more of your code structure. What package is Main.class in? is it in the same archive as "/System/entities.xml"?

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline Captain Awesome

Junior Member


Medals: 2


Hi


« Reply #7 - Posted 2010-11-17 17:11:40 »

The following is known to work, always, everywhere:
1  
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("System/entities.xml");


If it doesn't work, you might not have the JAR in your classpath.
That unfortunately returned null aswell :s
Also I'm not sure how to add the jar to the classpath since all I do is copy some resources and compiled class files from another jar.

Have a read of the javadoc; it explains how the path is resolved.

To summarize:

If the resource name begins with '/', then the path is absolute - taken from the root of the class path. (i.e. it will find resources that reside in what would be otherwise called the default package)
Otherwise, the resource is relative to the package folder of the Class you are invoking the method upon.

So:

1  
somePackage.SomeClass.class.getResourceAsStream("data/some.file");


will give the same results as:

1  
AnyClass.class.getResourceAsStream("/somePackage/data/some.file");


I'm not sure why your initial example doesn't work; you might need to show a little more of your code structure. What package is Main.class in? is it in the same archive as "/System/entities.xml"?



That image shows the root-folder in my jar file. Main.class is located in the Game folder while my entities.xml file is located in the System folder.

I'm going to write my own class loader and see if that works. Thanks for your help guys, I really appreciate it Smiley
Offline Captain Awesome

Junior Member


Medals: 2


Hi


« Reply #8 - Posted 2010-11-17 18:55:53 »

Problem is solved now. Apparently there is difference between adding the entries to a jarfile as \System\entities.xml and as /System/entities.xml  Tongue
Offline CaptainJester

JGO Knight


Medals: 12
Projects: 2
Exp: 14 years


Make it work; make it better.


« Reply #9 - Posted 2010-11-18 12:57:36 »

Why aren't you using Ant or Maven to create your jar file?

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CopyableCougar4 (17 views)
2014-08-22 19:31:30

atombrot (28 views)
2014-08-19 09:29:53

Tekkerue (25 views)
2014-08-16 06:45:27

Tekkerue (23 views)
2014-08-16 06:22:17

Tekkerue (15 views)
2014-08-16 06:20:21

Tekkerue (22 views)
2014-08-16 06:12:11

Rayexar (61 views)
2014-08-11 02:49:23

BurntPizza (39 views)
2014-08-09 21:09:32

BurntPizza (31 views)
2014-08-08 02:01:56

Norakomi (38 views)
2014-08-06 19:49:38
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!