检查是否正确设置文件路径和是否有写入存储的权限。可以使用以下代码作为参考:
// 检查是否有写入存储的权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// 没有权限,则请求权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
} else {
// 有权限则保存视频
saveVideo();
}
// 保存视频到指定路径
private void saveVideo() {
String folderName = "MyVideos";
String fileName = "MyVideo.mp4";
String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/" + folderName + "/" + fileName;
// 确保文件夹存在
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), folderName);
if (!folder.exists()) {
folder.mkdirs();
}
// 保存视频
File file = new File(filePath);
try {
FileOutputStream fos = new FileOutputStream(file);
// 写入视频数据
fos.write(videoData);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
其中,MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE
是请求存储权限时用到的请求码,videoData
是视频数据。