2010-10-03 38 views

回答

9

這將.apk文件資產文件夾的「剪貼畫」子文件夾中的所有文件複製到你的應用程序的文件夾在SD卡上的「剪貼畫」子文件夾:使用時

String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
    String basepath = extStorageDirectory + "/name of your app folder on the SD card"; 
//... 

// in onCreate 
File clipartdir = new File(basepath + "/clipart/"); 
     if (!clipartdir.exists()) { 
      clipartdir.mkdirs(); 
      copyClipart();  
     } 

private void copyClipart() { 
     AssetManager assetManager = getResources().getAssets(); 
     String[] files = null; 
     try { 
      files = assetManager.list("clipart"); 
     } catch (Exception e) { 
      Log.e("read clipart ERROR", e.toString()); 
      e.printStackTrace(); 
     } 
     for(int i=0; i<files.length; i++) { 
      InputStream in = null; 
      OutputStream out = null; 
      try { 
       in = assetManager.open("clipart/" + files[i]); 
       out = new FileOutputStream(basepath + "/clipart/" + files[i]); 
       copyFile(in, out); 
       in.close(); 
       in = null; 
       out.flush(); 
       out.close(); 
       out = null; 
      } catch(Exception e) { 
       Log.e("copy clipart ERROR", e.toString()); 
       e.printStackTrace(); 
      }  
     } 
    } 
    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); 
     } 
    } 
+0

哪裏該代碼必須以確保它只會發生一次,在安裝,然後刪除自APK文件? – joon 2013-05-19 15:59:54

+0

@joon:你可以使用[link](http://developer.android.com/reference/android/content/SharedPreferences.html)來保存一個布爾值,以確保它只發生一次。順便說一下,你不能從apk中刪除文件。@查看更多:[link](http://developer.android.com/guide/topics/resources/providing-resources.html) – Justin 2014-03-03 16:05:53

0

我經歷了類似的問題mkdirs(),然而因爲運行命令:

MKDIR一/二

失敗Linux上,則該方法http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdirs() subse也會失敗。我想這意味着無法在Android上使用mkdirs?我(可能是相當哈克)的變通是單獨創建每個必要的目錄:

String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
new File(extStorageDirectory + "/one/").mkdirs(); 
new File(extStorageDirectory + "/one/two/).mkdirs(); 
+0

[File.mkDirs() ](http://developer.android.com/reference/java/io/File.html#mkdirs%28%29)的作品。我已經在Android 2.1(API級別7) – Mudassir 2011-07-19 12:17:17

相關問題