andy boot
andy boot

Reputation: 11727

Android - reading txt files from external jar

I have a jar compiled with core jdk.

It contains a java class which reads a txt file. It has a test which proves that this class works correctly.

If I include this jar in my android project and then call the java class that reads the txt file. It fails reporting: java.io.FileNotFoundException and adding a '/' to the path of the txt file which I wanted to load.

Is Android's security model stopping the txt file from being read?

My Project structure:

Android Module:

src/Loader.java [calls GetName.java]

Java Module:

test/TestGetName.java [calls GetName.java]

src/GetName.java

resources/names.txt

Summary:

TestGetName.java works

Loader.java fails. A FileNotFoundException is thrown inside GetName

Upvotes: 2

Views: 2280

Answers (3)

Martin Rajniak
Martin Rajniak

Reputation: 640

I don't know why but accepted answer didn't work for me.

Build System : Gradle

Working environment : Android Studio

I also included resources from external jar. But in order to use them I had to include full path also.

this.getClass().getResourceAsStream("/template/login.xml")

Hope this helps someone and prevents him from spending 3 hours banging his head against the wall to find an answer.

Upvotes: 0

andy boot
andy boot

Reputation: 11727

Figured it out in the end. I need a condition to see if I am loading the file locally or as a resource. There is probably a neater way to do this without using a conditional.

    String source = "resources/inputfile.txt";
    BufferedReader fin;

    InputStream inputStream = getClass().getResourceAsStream(source.substring(source.lastIndexOf("/")));
    if (inputStream != null) {
        fin = new BufferedReader(new InputStreamReader(inputStream));
    } else {
        fin = new BufferedReader(new FileReader(new File(source)));
    }

Thanks for the hints about reading as a resource user77777777

Upvotes: 2

Ron
Ron

Reputation: 24233

It doesnt seem like the Android stopping it from accessing the file because the exception is FileNotFoundException. You should check the detailed message to confirm that. Catch the Exception and print the detailed message. That will give you a better idea. Also recheck the file path.

EDIT: Try passing the resource name only.

getClassLoader().getResource("names.txt");

Upvotes: 1

Related Questions