2

I recently just start to using Android Studio for my programming study.

I've faced a problem today which is keep getting "null" when I using getResourceAsStream to read a properties file from JUNIT TEST.

I used to locate the .properties file under "src" directory when I was using Eclipse. But in Android Studio, it won't work.

Here is the code that part of a class called BeanFactory,:

private static Properties properties;

static {
    properties = new Properties();
    InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
    try {
        properties.load(is);
    }catch (IOException e) {
        e.printStackTrace();
    }
}

In Eclipse, I located the the prop file under src, and it works just fine.

But in Android Studio, I've tried put the "bean.properties" file in several different directory. Such as /src, or/src/main/java, nothing worked out.

Where should I put the prop file? Is there any configurations that I should do for this?

Zijian Wang
  • 334
  • 2
  • 7

3 Answers3

1

Placing resources into assets is not acceptable in some cases. I solved this problem by packing required resourses into special jar file and placing this jar into libs directory.Thus you still can access them via standard Java technique.

0

There are two issues. In general resources are stored in a jar, with the compiled .class files. getResource and getResourceAsStream are methods of a class. The resource is searched in the jar of this class (in general). So with inheritance getClass().getResource("...") might be dangerous.

The second, more grave pitfall is, that the path is relative to the package (directory) of the class, unless you use "/...".

Another way is to use ResourceBundle instead of Properties. ResourceBundle has a PropertiesResourceBundle for *.properties.

ResourceBundle properties = ResourceBundle.getBundle("bean");
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
-1

try this:
1.put your own bean.properties file in app/src/main/assets
2.change you code to:

private static Properties prop;

static {
    prop = new Properties();
    try {
        InputStream is = IWorkApplication.getInstance().getResources().getAssets().open("bean.properties", Context.MODE_PRIVATE);
        prop.load(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

PS.IWorkApplication.getInstance() is define in my own application class.
Hope to be useful

wml
  • 1
  • 1
  • This will work, but in most cases you don't really want those files to be included in the app build, since they are dummy data for unit tests. – Oyvind Feb 10 '15 at 23:00