1

I am testing something.

I created assets folder in packages/apps/Camera/ and added the test.txt file in the folder.

But when I accessed the file in the onCreate() method according the following code fragment, I found I can't get the file.

    File file = new File("/assets/test.txt");
    BufferedReader reader = null;
    try {
        Log.v("jerikc","read the file");
        reader = new BufferedReader(new FileReader(file));
        String tempString = null;
        int line = 1;

        while ((tempString = reader.readLine()) != null) {

            Log.v("jerikc","line " + line + ": " + tempString);
            line++;
        }
        reader.close();
    } catch (IOException e) {
        Log.v("jerikc","exception");
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e1) {
            }
        }
    }

The log were :

V/jerikc (3454): read the file

V/jerikc (3454): exception

I think I add the wrong path.("/assets/test.txt") . So what's the right path?

Some other informations:

Where my real code is a Util Class, there isn't the context. If I add the context, the code structure will have a big change.

Thanks.

Jerikc XIONG
  • 3,517
  • 5
  • 42
  • 71

2 Answers2

1

You have to read assets like below

AssetManager mAsset = context.getAssets();

InputStream is = mAsset.open("test.txt");
nandeesh
  • 24,740
  • 6
  • 69
  • 79
1

you can get the path from assest folder by this way...try this...

File file = new File("file:///assets/test.txt");

instead of this..

File file = new File("/assets/test.txt");
Mehul Ranpara
  • 4,245
  • 2
  • 26
  • 39