Reputation: 3464
So, I'm trying to save a mp4 file from a temp file to the picture directory. The tablet works fine. But it's not working on a samsung nexus. It's not even creating the directory.
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();
}
}
Anyone know what's wrong with my code?
Upvotes: 1
Views: 128
Reputation: 1522
Print the log of your destination path. I think it is having two slashes.(//).Because you are writing File.seperator+"/". Print the log and check the path.
Upvotes: 3
Reputation: 9540
Try this code:
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();
}
Add this function too:
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);
}
}
Upvotes: 1
Reputation: 4942
Change this line
File destination= new File(mediaStorageDir.getPath() + File.separator+"/"+videoFileName);
to this
File destination= new File(mediaStorageDir.getPath() + File.separator + videoFileName);
you are using an extra "/"
which is not required when you are using File.separator
. Check if this solve your problem
Upvotes: 1