read file from assets

前端 未结 18 2443
终归单人心
终归单人心 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

    You can load the content from the file. Consider the file is present in asset folder.

    public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
        AssetManager am = context.getAssets();
        try {
            InputStream is = am.open(fileName);
            return is;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String loadContentFromFile(Context context, String path){
        String content = null;
        try {
            InputStream is = loadInputStreamFromAssetFile(context, path);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            content = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return content;
    }
    

    Now you can get the content by calling the function as follow

    String json= FileUtil.loadContentFromFile(context, "data.json");
    

    Considering the data.json is stored at Application\app\src\main\assets\data.json

提交回复
热议问题