来源:https://blog.csdn.net/anjingshuai/article/details/84682779
开发过程中碰到将文件存储到手机中时,要先判断是否有sd卡,如下所示
- // 判断是否有SD卡
- private static boolean ExistSDCard() {
- if (android.os.Environment.getExternalStorageState().equals(
- android.os.Environment.MEDIA_MOUNTED)) {
- return true;
- } else
- return false;
- }
如果存在,则要获取sd卡的根目录路径,在目录下创建新的文件夹,sd卡根目录路径如下:
- public static String SDCARDPATH = Environment.getExternalStorageDirectory()
- .getPath();
然后是将要复制的文件写到sd卡下新建的文件夹内,代码如下:
- private void copyzipfileToLocalDir(final String path, final String filename) {
- File file = new File(path);
- if (file.exists()) {
- Uri uri = Uri.fromFile(file);
- Intent intent = new Intent(Intent.ACTION_VIEW, uri);
- intent.setClass(MainActivity. this, TestActivity.class);
- startActivity(intent);
- return;
- }
- pdlog = new ProgressDialog(this);
- pdlog.setMessage( "正在复制文件...");
- pdlog.show();
- new Thread() {
- public void run() {
- try {
- InputStream input = getApplicationContext().getAssets()
- .open(filename);
- File f = new File(path);
- if (f.exists()) {
- return;
- }
- File file = f.getParentFile();
- // SDCARD/CN/ZNsql====================path
- if (!file.exists()) {
- file.mkdir();
- }
- FileOutputStream fout = new FileOutputStream(f);
- byte[] buff = new byte[1024];
- int len = 0;
- while ((len = input.read(buff)) > 0) {
- fout.write(buff, 0, len);
- }
- fout.close();
- input.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- handler.sendEmptyMessage( 1);
- };
- }.start();
- }
- private Handler handler = new Handler() {
- public void handleMessage(android.os.Message msg) {
- switch (msg.what) {
- case 1:
- if (pdlog != null) {
- if (pdlog.isShowing()) {
- pdlog.cancel();
- }
- ;
- }
- // jump
- File file = new File(SDCARDPATH "androidtest.pdf");
- if (file.exists()) {
- Uri uri = Uri.fromFile(file);
- Intent intent = new Intent(Intent.ACTION_VIEW, uri);
- intent.setClass(MainActivity. this, TestActivity.class);
- startActivity(intent);
- }
- break;
- default:
- break;
- }
- };
- };
这样就将assets下的文件写入了外置sd卡,对于一些不支持外置存储卡的Android手机,我们可以将文件写入机身内存,也就是俗称的ROM中,RomPath= Environment.getDataDirectory().getPath();当判断到没有外置sd卡时就可以把path换成这个RomPath即可,这样就完成了将文件写入机身内存中。