0

如何在 Android 中首次运行应用程序时将文件从资产文件夹复制到 SD 卡中?我需要知道确切的步骤。

4

3 回答 3

1
private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    for(String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          out = new FileOutputStream(outFile);
          copyFile(in, out);
          in.close();
          in = null;
          out.flush();
          out.close();
          out = null;
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }       
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}
于 2013-10-19T17:08:27.213 回答
1

1.首次运行:检查您放置的 sharedPreference 值是否以前存在。如果不是,这是第一次运行,您还应该添加该值。如果它存在,它不是第一次运行。例子:

SharedPreferences pref=PreferenceManager.getdefaultsharedpreferences‎(this);
if(!pref.contains("firstInstall"))
  {
  //first install, so do some stuff...
  pref.edit().putBoolean("firstInstall",true).commit();
  }

2.在清单中添加写入外部存储的权限。

3.使用 inputStream 从 assets 中读取文件,例如:

 AssetManager assetManager = getAssets();
 InputStream is assetManager.open("myFile.txt");

4.使用 outputStream 从 inputStream 写入目标文件,如下:

  FileOutputStream os=null;
  try
    {
    File root = android.os.Environment.getExternalStorageDirectory(); 
    File file = new File(root , "myFile.txt");
    os = new FileOutputStream(file);
    byte[] buf = new byte[1024];
    int len;
    while ((len = is.read(buf)) > 0) 
       os .write(buf, 0, len);
    }
  finally
    {
    if(is!=null)
      is.close();
    if(os!=null)
      os.close();
    }
于 2013-10-19T16:46:13.743 回答
0

使用标准的 JAVA I/O。用于Environment.getExternalStorageDirectory()访问外部存储(在某些设备上是 SD 卡)的根目录。您必须将此添加到您的权限中:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 当您拥有路径时,您可以使用以下方法复制文件:

public void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}
于 2013-10-19T16:35:30.530 回答