復制文件夾的工具類

這幾天公司項目想拿數(shù)據(jù)庫的數(shù)據(jù),但是安卓設備沒有root權限,所以自己想了個辦法:直接把所有data/data/app下的所有文件全部復制下來了,然后就想看啥數(shù)據(jù)看啥數(shù)據(jù),文件結構如下:


image.png

具體的操作如下:

  1. 一個復制文件夾的工具類

public static void copyPath(final File oldPath, final File newPath){
    if(!oldPath.isDirectory() || !newPath.isDirectory()){
        new IllegalArgumentException("File mast is Directory");
    }
    if(newPath.exists()){
        new IllegalArgumentException("newFile not is exists");
    }
    try{
        //io耗時操作,放在子線程
        new Thread(new Runnable() {
            @Override
            public void run() {
                copyFiles(oldPath,oldPath.getPath(),newPath.getPath());
            }
        }).start();
    }catch (Exception e){
        e.printStackTrace();
    }
}

public static void copyFiles(File oldFile,String oldPath,String newPath){
    File[] files = oldFile.listFiles();
    for (int i = 0; i < files.length; i++) {
        System.out.println(files[i].getPath());
        if(files[i].isDirectory()){
            createDirectory(files[i],oldPath,newPath);
            File[] fs = files[i].listFiles();
            if(fs != null && fs.length != 0){//遍歷文件夾的下一層
                copyFiles(files[i],oldPath,newPath);
            }
        }else if(files[i].isFile()){
            copyFile(files[i],oldPath,newPath);
        }
    }
}

public static void copyFile(File file,String oldPath,String newPath){
    String path = file.getPath();
    String nPath = path.replace(oldPath, newPath);
    File nfile = new File(nPath);
    InputStream in = null;
    OutputStream out = null;
    try {
        in = new FileInputStream(file);
        out = new FileOutputStream(nfile);
        byte[] bs = new byte[1024];
        int len = -1;
        while((len = in.read(bs))!= -1){
            out.write(bs, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            if(in != null){
                in.close();
            }
            if(out != null){
                out.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
}

public static void createDirectory(File dir,String oldPath,String newPath){
    String path = dir.getPath();
    String nPath = path.replace(oldPath, newPath);
    File file = new File(nPath);
    file.mkdirs();
}

  1. 然后調用就可以了

    File f = new File(Environment.getDataDirectory().getPath()+"/data/"+this.getPackageName() + "/");
    FileUtil.copyPath(f,Environment.getExternalStorageDirectory());

3.sql數(shù)據(jù)庫結構可以參照這篇博客sqllite的數(shù)據(jù)結構

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容