1、首先需要给应用配置权限才可以在存储卡创建文件,配置参照:
Android 在存储卡(sdcard)创建文件夹/文件失败
2、代码:
public void copyTo(String fromPath, String toPath){ // 复制位置 // opPath:mnt/sdcard/lcuhg/health/ // mnt/sdcard:表示sdcard File toFile = new File(toPath); // 如果不存在,创建文件夹 if(!toFile.exists()){ boolean isCreate = toFile.mkdirs(); // 打印创建结果 Log.i("create dir", String.valueOf(isCreate)); } try { // 根据文件名获取assets文件夹下的该文件的inputstream InputStream fromFileIs = context.getResources().getAssets().open(fromPath); int length = fromFileIs.available(); //获取文件的字节数 byte[] buffer = new byte[length]; //创建byte数组 FileOutputStream fileOutputStream = new FileOutputStream(toFile+"/zhike.zip"); //字节输入流 BufferedInputStream bufferedInputStream = new BufferedInputStream(fromFileIs); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); int len = bufferedInputStream.read(buffer); while(len != -1){ bufferedOutputStream.write(buffer, 0, len); len = bufferedInputStream.read(buffer); } bufferedInputStream.close(); bufferedOutputStream.close(); fromFileIs.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }