views:

918

answers:

2

Hi, 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?

+5  A: 

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.

Max Gontar
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
Thanks for your help, coldice
nixau
:) 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.
Max Gontar
@nixau it's "too lazy"
Fostah
@Fostah, yep. It's a shame that you cannot edit comments in StackOverflow.com (
nixau
@coldice, actually I'm building my project with Ant build file and use Eclipse just as kinda sophisticated notepad.
nixau
@nixau, I see. You may try to use <includes> or something like that.
Max Gontar
A: 

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().

Fostah