簡體   English   中英

如何在Android首次運行應用程序時將文件從我的資產文件夾復制到我的SD卡?

[英]How can I copy a file from my assets folder into my SD card at first run of the app in Android?

如何在Android首次運行應用程序時將文件從我的資產文件夾復制到我的SD卡? 我需要知道確切的步驟。

1.first run:檢查你之前存在的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從資產中讀取文件,如下所示:

  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(); } 
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);
    }
}

使用標准JAVA I / O. 使用Environment.getExternalStorageDirectory()來到外部存儲的根目錄(在某些設備上,它是SD卡)。 您必須將此添加到您的persmissions中: <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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM