- 新建一個Android Studio項目。
- 在main文件夾下爱沟,新建assets文件夾癣疟,得到app/src/main/assets。把需要拷貝的文件復(fù)制/粘貼到其中惕虑。
我這里放了2個文件坟冲,01.jpg和02.jpg磨镶。
- 在AndroidManifest.xml中溃蔫,授予 寫外部存儲 的權(quán)限。
在<application>外加入:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- 修改
MainActivity.java
文件琳猫。
package ai.nixie.copyassets;
/*
Copy all the files in assets folder to your smartphone
From: app/src/main/assets
To: /sdcard/Android/data/packageName/files/
*/
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
copyAssets();
}
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);
}
if (files != null) 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);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
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);
}
}
}
- 驗證伟叛。
開命令行,adb shell進入手機脐嫂,可以在/sdcard/Android/data/包名/files/
目錄中统刮,找到我們要拷貝的文件。
- 幾個常用的目錄
String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
Log.d(TAG, "getExternalStorageDirectory: " + sdcardPath);
// getExternalStorageDirectory: /storage/emulated/0
String dataDir = getFilesDir().toString();
Log.d(TAG, "getFilesDir(): " + dataDir);
//getFilesDir(): /data/user/0/ai.nixie.copyassets/files
String externalFilesDir = getExternalFilesDir(null).toString();
Log.d(TAG, "getExternalFilesDir: " + externalFilesDir);
//getExternalFilesDir: /storage/emulated/0/Android/data/ai.nixie.copyassets/files
PackageManager packageManager = getPackageManager();
String str =getPackageName();
try {
PackageInfo pi = packageManager.getPackageInfo(str, 0);
str = pi.applicationInfo.dataDir;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Log.d(TAG, "applicationInfo.dataDir: " + str);
//applicationInfo.dataDir: /data/user/0/ai.nixie.copyassets
Android Studio v2.3中測試通過账千。
References
https://stackoverflow.com/questions/4447477/how-to-copy-files-from-assets-folder-to-sdcard