I have a java .jar library, and from there i'm trying to access a file of my Android project with:
InputStream inputStream = getClass().getResourceAsStream("/folder/data.txt");
someMethod(inputStream); // inputStream is null
But the inputStream
is always null
. I'm confused about where should i put my /folder/data.txt
in order to
be able to find it from the .jar.
From within the .jar project i can find the data.txt, doing the following in eclipse:
MyProject > properties > java build path > libraries > Add class folder
and this code:
InputStream inputStream = getClass().getResourceAsStream("/data.txt"); // without the folder
This is the structure of the Java Project:
MyJavaProject
- src
- com.example
- something.java
- folder
- data.txt
Now, inside the Android Project i try to do the same but i keep getting null (inputStream):
MyAndroidProject
- src
- several packages
- folder
- data.txt
- libs
- my jar
Where should i put my data.txt? or should i change something in my .jar
I've read a lot of similar questions but i haven't found a solution. I've also read about getResourceAsStream()
but i'm obviously not getting it.
getResourceAsStream()
isn't terribly useful in android. It refers to files embedded in a JAR or classpath container, not android Resources. You probably want to use the android assets
feature instead. You can simply place the asset file ("data.txt"
) under your project's assets/
directory.
To get an InputStream
for the asset, you can use the AssetsManager
, like this (error handling is omitted for clarity:
// get the assets manager from your activity or `Context`
final AssetsManager am = getAssets();
final InputStream in = am.open("data.txt");
// do stuff with the input stream
Another approach is to use Resources
instead, but this depends on the contents of data.txt
Resources are intended for data types that android knows how to load and parse, such as drawables, strings, and various xml files. Assets are for raw data that you are going to read and parse yourself.