Skip to content Skip to sidebar Skip to footer

Renaming File Extensions In Android

I am able to change file extensions, for example, from '.mp4' to '.xmp4' but instead of changing extension, i simply want to add a '.' before a file name for example 'mikey.jpg' to

Solution 1:

first you do String fileName = listFile[i].getName(); , which should give you the name, next you do String fullPath = listFile[i].getAbsolutePath(); to get the full path, then you do int indexOfFileNameStart = fullPath.lastIndexOf(fileName) , then you get a string builder instance from fullPath like so StringBuilder sb = new StringBuilder(fullPath); , now you call the insert method on sb sb.insert(indexOfFileNameStart, "."), now sb should have the string you desire, just construct it to string sb.toString()

Ill add this in code

private String putDotBeforeFileName(File file) {
    StringfileName= file.getName();
    StringfullPath= file.getAbsolutePath();
    intindexOfFileNameStart= fullPath.lastIndexOf(fileName);
    StringBuildersb=newStringBuilder(fullPath);
    sb.insert(indexOfFileNameStart, ".");
    StringmyRequiredFileName= sb.toString();
    file.renameTo(newFile(myRequiredFileName));
    return myRequiredFileName;
}

EDIT

This is how you can use the above method in your code

publicvoidwalkdir(File dir) {
    File listFile[] = dir.listFiles();
    if (listFile != null) {
        for (int i = 0; i < listFile.length; i++) {
            if (listFile[i].isDirectory()) {
                walkdir(listFile[i]);
            } else {
                String fPath = listFile[i].getPath();
                for (String ext : TARGET_EXTENSIONS) {
                    if(fPath.endsWith(ext)) {
                        putDotBeforeFileName(listFile[i]);
                    }
                }
            }
        }
    }
}

Post a Comment for "Renaming File Extensions In Android"