1. 程式人生 > >android 建立檔案和建立資料夾、將assets下檔案複製到指定目錄下

android 建立檔案和建立資料夾、將assets下檔案複製到指定目錄下

1.獲取APP當前目錄路徑:

 public String getPath(){
        File fileDire = getFilesDir();//獲取../data/應用的包名/files/ 目錄
        File cacheDire = getCacheDir();//獲取../data/應用的包名/files/ 目錄
        String filePath  = fileDire.toString();
        String cachePath  = cacheDire.toString();
        
        String rootpath = filePath.substring(0,filePath.lastIndexOf("/")); //擷取掉files   獲取../data/應用的包名/
        
        return rootpath;
    }

2.建立檔案:

public void creatFile(String path, String fileName) {
        File file = new File(path, fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

3.建立資料夾

public void creatFile(String path, String fileName) {
        File file = new File(path, fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

4.將assets下檔案複製到指定目錄下

首先在android studio 目錄結構切換到project上來在src/main下new->folder->assets folder建立assets目錄然後將檔案放到此資料夾下。

 public void copyfile(String filepath,String fileName,String assetsName) {
        try {
            if (!new File(filepath + "/" + fileName).exists()) {

                InputStream is = getResources().getAssets().open(assetsName);

                FileOutputStream fos = new FileOutputStream(filepath + "/" + fileName);
                byte[] buffer = new byte[7168];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }