Android將assets下的文件存入內存

存入緩存

/**
     * 將asset文件寫入緩存
     */
    public static boolean copyAssetToCache(Context context, String fileName) {
        try {
            File cacheDir = context.getCacheDir();
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }
            File outFile = new File(cacheDir, fileName);
            if (!outFile.exists()) {
                boolean res = outFile.createNewFile();
                if (!res) {
                    return false;
                }
            } else {
                if (outFile.length() > 10) {//表示已經寫入一次
                    return true;
                }
            }
            InputStream is = context.getAssets().open(fileName);
            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }
複製代碼

存入內存

public static void copyAssetToSD(Context context, String fileName) {
        try {
            boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
            if (!sdCardExist)
                return;

            File dirFile = new File(Environment.getExternalStorageDirectory() + "/taxi");
            if (!dirFile.exists())
                dirFile.mkdir();

            File file = new File(Environment.getExternalStorageDirectory() + "/taxi/"+fileName);
            if (file.exists())
                return;

            InputStream ins = context.getAssets().open(fileName);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int l = 0;
            while ((l = ins.read(buffer)) != -1) {
                fos.write(buffer, 0, l);
            }
            fos.flush();
            fos.close();
            ins.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
複製代碼
相關文章
相關標籤/搜索