0

I need to read a resource file from classpath in my BlackBerry application. The directory structure of my project is pretty common: under src directory there are 2 child dirs, one represents source packages root, another - resources root.

When I try to read any resource from classpath Class.getResourceAsStream method retures null

    InputStream rStream = null;
    String path = "/res/default_config.xml";
    try {
        rStream = getClass().getResourceAsStream(path);
    } finally {
        try {
            if (rStream != null) {
                byte[] data = IOUtilities.streamToBytes(rStream);
                System.out.println(new String(data));
                rStream.close();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

How should I read classpath resource properly?

Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114
nixau
  • 1,095
  • 1
  • 14
  • 27

3 Answers3

7

And have you tried to put xml file directly into src folder and use getClass().getResourceAsStream("default_config.xml"); ?

Actually cannot reproduce.
Tested on simulator 8800 eJDE 4.2.1.
File was placed in src/res/ folder.

Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114
  • I works when I pass "/default_config.xml" as a parameter. RIM guys were to lazy to implement navigation on classpath packages... o_O – nixau Oct 01 '09 at 14:57
  • 1
    :) You're welcome! But by some reason it work for me to use "/res/default_config.xml" class path, and file is placed in [project folder]\src\res. Other feature is that we have to refresh project in eclipse to make all resources be compiled properly during build. – Maksym Gontar Oct 01 '09 at 15:41
  • @Fostah, yep. It's a shame that you cannot edit comments in StackOverflow.com ( – nixau Oct 01 '09 at 16:04
  • @coldice, actually I'm building my project with Ant build file and use Eclipse just as kinda sophisticated notepad. – nixau Oct 01 '09 at 16:06
  • 1
    @nixau, I see. You may try to use or something like that. – Maksym Gontar Oct 01 '09 at 16:46
0

Even though it's generated as a COD file for running on the device, the JAR file is also created each build. It might be worth checking to make sure your xml file is being put in the directory that you expect it to be in as you can definitely store resources in sub-directories in your application and retrieve them using getClass().getResourceArStream();

Lucifer
  • 29,392
  • 25
  • 90
  • 143
Fostah
  • 11,398
  • 10
  • 46
  • 55
0

I think you specified the path as incorrect way. You just remove the / from the beginning of the path you specified. If you are specifying /. then it will check for you resource folder

Dan McClain
  • 11,780
  • 9
  • 47
  • 67
Siraj Shan
  • 41
  • 3