安卓:从assets目录下复制文件到指定目录

有些时候我们直接将某些资源文件内置到apk中,便于直接使用。

1.首先将文件放置在项目/app/src/main/assets目录中

2.功能代码:

public void copyFile(String filename) {
        InputStream in = null;
        FileOutputStream out = null;
     // path为指定目录 String path
= this.context.getApplicationContext().getFilesDir().getAbsolutePath() +"/"+filename; // data/data目录 File file = new File(path); if (!file.exists()) { try { in = this.context.getAssets().open(filename); // 从assets目录下复制 out = new FileOutputStream(file); int length = -1; byte[] buf = new byte[1024]; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); } out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } }

3.调用方法: coptFile("文件名") 

原文地址:https://www.cnblogs.com/halfsaltedfish/p/10416921.html