read file from assets

前端 未结 18 2248
终归单人心
终归单人心 2020-11-21 22:47
public class Utils {
    public static List getMessages() {
        //File file = new File(\"file:///android_asset/helloworld.txt\");
        AssetMan         


        
18条回答
  •  难免孤独
    2020-11-21 23:34

    Here is a method to read a file in assets:

    /**
     * Reads the text of an asset. Should not be run on the UI thread.
     * 
     * @param mgr
     *            The {@link AssetManager} obtained via {@link Context#getAssets()}
     * @param path
     *            The path to the asset.
     * @return The plain text of the asset
     */
    public static String readAsset(AssetManager mgr, String path) {
        String contents = "";
        InputStream is = null;
        BufferedReader reader = null;
        try {
            is = mgr.open(path);
            reader = new BufferedReader(new InputStreamReader(is));
            contents = reader.readLine();
            String line = null;
            while ((line = reader.readLine()) != null) {
                contents += '\n' + line;
            }
        } catch (final Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ignored) {
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }
        }
        return contents;
    }
    

提交回复
热议问题