Ad

Android OldFile.renameTo(newFile) Not Working On Lower Android

- 1 answer

Hello fellow developers. I've been reading on here a lot, but can't find any solution for my problem.

I have an image file from a Camera Intent which I need to rename. IMPORTANT: It works on Android 8.1 but doesn't work on 5.1.1 as tested.

I have no idea why, but came closer to the troublemaker. It's the renameTo(), which doesn't do anything, or at least I don't know of anything it does. Here is the part of the code:

imgFinalName = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            format + ";" + lkwNr + ";" + telefonNr + ".jpg");
    if (imageFile.exists()){
        Log.d("Mati","Old File exists");
    }else{
        Log.d("Mati","Old File doesn't exist");
    }
    imageFile.renameTo(imgFinalName);
    Log.d("Mati","New Filename: " + imgFinalName.getName());
    Log.d("Mati","Path: " + imgFinalName.getAbsolutePath());
    if (imageFile.exists()){
        Log.d("Mati","Old File exists");
    }else{
        Log.d("Mati","Old File doesn't exist");
    }
    if (imgFinalName.exists()){
        Log.d("Mati","New File exists");
    }else{
        Log.d("Mati","New File doesn't exist");
    }

The Log results are as followed:

Old file exists

New Filename: 2017-12-04_21:39:03;235;123123.jpg

Path: /storage/sdcard/Pictures/2017-12-04_21:39:03;235;123123.jpg

Old File exists

New File doesn't exist

So as you can see, the Old File exists, then I invoke the renameTo method, the old file still exists and the new file doesn't.

As I said, it works on Android 8.1, but doesn't on 5.1.1 and I really have no idea why... Would be nice if you guys had a solution. Feel free to ask questions

Ad

Answer

Just as I turned off Android Studio and wanted to go to sleep, I thought about the SimpleDateFormat.

As you can see in the filename, its:

SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String format = s.format(new Date());

I changed it now to:

SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
String format = s.format(new Date());

And it works. Note that the "-", "_" and ":" work in android 8.1. Those options were added in the future I guess. Anyway, what a stupid mistake, but glad I found it. Sorry for bothering.

Ad
source: stackoverflow.com
Ad