文件拷贝涉及到sd卡的读写,所有需要在配置文件中添加读写权限。因为没有使用动态权限,此方法仅限于,targetSdkVersion小于等于22的项目。
public String copyVideoToSD(Context context, String fileName) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/" + getPackageName() + "/";
InputStream inputStream;
try {
//判断文件是否存在
File file1 = new File(path + "/" + fileName);
if (!file1.exists()) {
Toast.makeText(context, "正在处理", Toast.LENGTH_LONG).show();
inputStream = getAssets().open(fileName);
File file = new File(path);
//当目录不存在时创建目录
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream fileOutputStream = new FileOutputStream(path + "/" + fileName);// 保存到本地的文件夹下的文件
byte[] buffer = new byte[1024];
int count = 0;
while ((count = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
} else {
Toast.makeText(context, "已存在", Toast.LENGTH_LONG).show();
}
return path + fileName;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
//获取到拷贝后的视频播放地址
String path_url=copyVideoToSD("xxx.mp4");
//其他地方使用播放地址
String path_url2 =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/{包名}/xxx.mp4";