Android path to asset txt file

2019-01-05 04:00发布

I'm doing:

FileReader fin = new FileReader("file:///android_asset/myFile.txt");

in an Android project and many variations. At runtime I get a file not found exception. The file is present and correct in the assets folder, so my path must be wrong.

What is the absolute path I need here?

6条回答
不美不萌又怎样
2楼-- · 2019-01-05 04:19
AssetManager am = context.getAssets();
InputStream fs = am.open("myFile.txt");
查看更多
叼着烟拽天下
3楼-- · 2019-01-05 04:20

Can you use something like

    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(context.getAssets().open("fileName.txt")));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
查看更多
smile是对你的礼貌
4楼-- · 2019-01-05 04:21

I found that if you are using an IDE like Eclipse you may need to do a clean -- or delete the API in the bin directory. It seems that the assets isn't getting updated when you do a build.

查看更多
forever°为你锁心
5楼-- · 2019-01-05 04:28

Its not reading it because all assets in assets folder are compressed, try changing its extension to .mp3 then read it in, that should stop it from being compressed.

查看更多
何必那么认真
6楼-- · 2019-01-05 04:35
    InputStream is = getResources().getAssets().open("terms.txt");
    String textfile = convertStreamToString(is);

public static String convertStreamToString(InputStream is)
            throws IOException {
            Writer writer = new StringWriter();

            char[] buffer = new char[2048];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is,
                        "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            String text = writer.toString();
            return text;
    }
查看更多
【Aperson】
7楼-- · 2019-01-05 04:37
AssetFileDescriptor descriptor = getAssets().openFd("myfile.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());

Try using the above with FileDescriptors. Seems to be the most foolproof way I've found to gather asset paths.

查看更多
登录 后发表回答