所以,我正在尝试将mp4文件从临时文件保存到图片目录。平板电脑工作正常。但它不适用于三星关系。它甚至没有创建目录。
private void moveFileToGallery() {
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
VIDEO_DIRECTORY_NAME);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(VIDEO_DIRECTORY_NAME, ": Failed to create directory");
return;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String videoFileName = "VID_"+timeStamp+".mp4";
File source= new File("/sdcard/myvideo.mp4");
File destination= new File(mediaStorageDir.getPath() + "/"+videoFileName);
source.renameTo(destination);
Toast.makeText(getApplicationContext(), "Video Saved to Gallery!", Toast.LENGTH_LONG).show();
}
}
有人知道我的代码有什么问题吗?
答案 0 :(得分:3)
打印目标路径的日志。 我认为它有两个斜杠。(//)。因为你正在编写File.seperator +“/”。 打印日志并检查路径。
答案 1 :(得分:1)
更改此行
File destination= new File(mediaStorageDir.getPath() + File.separator+"/"+videoFileName);
到这个
File destination= new File(mediaStorageDir.getPath() + File.separator + videoFileName);
您正在使用额外的"/"
,使用File.separator
时不需要。检查这是否解决了您的问题
答案 2 :(得分:1)
试试这段代码:
private void moveFileToGallery() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES),"myvideo");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("myvideo", ": Failed to create directory");
return;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String videoFileName = "VID_"+timeStamp+".mp4";
File source= new File(Environment.getExternalStorageDirectory() + File.separator + "myvideo.mp4");
File destination= new File(mediaStorageDir.getPath() + File.separator + videoFileName);
try {
InputStream inputStream = getContentResolver().openInputStream(Uri.fromFile(source));
FileOutputStream fileOutputStream = new FileOutputStream(destination);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Video Saved to Gallery!", Toast.LENGTH_LONG).show();
}
也添加此功能:
public static void copyStream(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}