Android 连接U盘 备份应用数据库

 判断U盘是否插入,否则提醒,获取该应用数据库路径,并导出到U盘

     //获取U盘路径
     String usbPath = FileTools.getStoragePaths(getAttachContext());
     if (TextUtils.isEmpty(usbPath)) {
           ToastUtils.info("请插入U盘!");
      } else {
        try {//生成导出文件名称
           File dbFile = getContext().getDatabasePath("xxx.db");
           File file = new File(usbPath, "xxx" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".db");
           if (!file.exists()) {
               try {
                    file.createNewFile();
                    } catch (IOException e) {
                       e.printStackTrace();
                    }
                   }
                FileInputStream is = new FileInputStream(dbFile);
                FileOutputStream out = new FileOutputStream(file);
                byte[] buff = new byte[1024];
                int n = 0;
                   while ((n = is.read(buff)) > 0) {
                     out.write(buff, 0, n);
                }
                is.close();
                out.close();
                ToastUtils.success("备份成功");
            } catch (Exception e) {
        }
   }

 FileTools.java  工具类


import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;

/**
 * Android判断U盘插入,导出数据工具类
 */
public class FileTools {
    public final static String STORAGE_PATH = "/storage/emulated/0";
    public final static String SYSTEM_PATH = "/mnt/sdcard";
    public static final String NULL_FILE_TAG = "dev/null";//空文件过滤掉

    //得到usb路径
    public static String getStoragePaths(Context cxt) {

        StorageManager storageManager = (StorageManager) cxt.getSystemService(Context.STORAGE_SERVICE);
        try {
            Method method = StorageManager.class.getDeclaredMethod("getVolumePaths");
            method.setAccessible(true);
            Object result = method.invoke(storageManager);
            if (result != null && result instanceof String[]) {
                String[] pathes = (String[]) result;
                StatFs statFs;
                for (String path : pathes) {
                    if (path.equals(STORAGE_PATH)) {
                        path = SYSTEM_PATH;
                    }
                    if (!TextUtils.isEmpty(path) && new File(path).exists()) {
                        statFs = new StatFs(path);
                        if ((statFs.getBlockCount() * statFs.getBlockSize() != 0)) {
                            if (!path.contains(NULL_FILE_TAG) && !path.contains("sdcard")) {
                                return path;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return "";
    }

    //usb名字
    public static String getUsbDeviceLabel(Context context, String strMountPath) {

        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        try {

            Method getVolumeList = StorageManager.class.getDeclaredMethod("getVolumeList", new Class[0]);

            getVolumeList.setAccessible(true);

            Class<?> classStorageVolume = Class.forName("android.os.storage.StorageVolume");

            Method getPath = classStorageVolume.getDeclaredMethod("getPath", new Class[0]);

            Method getLabel = classStorageVolume.getDeclaredMethod("getUserLabel", new Class[0]);

            Object[] volumes = (Object[]) getVolumeList.invoke(storageManager, new Object[0]);

            if (volumes != null) {

                for (int i = 0; i < volumes.length; i++) {
                    String path = (String) getPath.invoke(volumes[i], new Object[0]);
                    String label = (String) getLabel.invoke(volumes[i], new Object[0]);
                    if (path.equals(strMountPath)) {
                        return label;
                    }
                }
            }
            if (!strMountPath.isEmpty()) {
                int subInt = strMountPath.lastIndexOf("/");
                strMountPath = strMountPath.substring(subInt + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strMountPath;
    }

    /**
     * 复制文件 <功能说明>
     *
     * @param @param oldPath
     * @param @param newPath
     */

    public static boolean copyFile(String oldPath, String newPath) {
        boolean isCopyFileSuccess = false;
        FileInputStream fis = null;
        RandomAccessFile raf = null;
        try {
            File oldFile = new File(oldPath);
            File newFile = new File(newPath);
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            if (oldFile.exists()) { //文件存在时
                fis = new FileInputStream(oldPath);
                raf = new RandomAccessFile(newFile.getPath(), "rwd");
                raf.setLength(0);//清除旧文件
                byte[] buf = new byte[3 * 1024 * 1024];
                int readline = 0;
                while ((readline = fis.read(buf)) != -1) {
                    raf.write(buf, 0, readline);
                }
                if (newFile.length() > 1) {
                    isCopyFileSuccess = true;
                } else {
                    newFile.delete();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //之前IO错误后就直接跳到catch,没有执行file.close的操作,现在把他们单独搞个try catch
        try {
            if (raf != null) {
                raf.close();
            }
            if (fis != null) {
                fis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isCopyFileSuccess;
    }

    //得到文件的Uri
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    public static File getFileByUri(Uri uri, Context context) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA},
                        buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();
            return new File(path);
        } else {
            //Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null;
    }

    public static String createFolder(String path) {
        if (TextUtils.isEmpty(path)) {
            return path;
        }
        File newlineFile = new File(path, "newline");
        if (!newlineFile.exists()) {
            newlineFile.mkdir();
        }
        return newlineFile.getAbsolutePath();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值