2

I can apply a prefix dot (".") to all the files having .gif extension successfully. For instance, rename "my_file.gif" to ".my_file.gif"). However, I want to remove this prefix dot again using code (AKA reverse it). I have tried, but it won't work. (simply does not remove the dot) below is my code and my approach -

this is the code for adding a dot prefix(which works fine)-

    // getting SDcard root path
    File dir = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath());
    walkdir(dir);
}
//detect files having these extensions and rename them
public static final String[] TARGET_EXTENSIONS = { "gif"};
public void walkdir(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]);
                    }
                }
            }
        }
    }
}

private String putDotBeforeFileName(File file) {
    String fileName = file.getName();
    String fullPath = file.getAbsolutePath();
    int indexOfFileNameStart = fullPath.lastIndexOf(fileName);
    StringBuilder sb = new StringBuilder(fullPath);
    sb.insert(indexOfFileNameStart, ".");
    String myRequiredFileName = sb.toString();
    file.renameTo(new File(myRequiredFileName));
    return myRequiredFileName;
  }
}                                                

and this is my approach for removing the dot prefix which doesn't work (no force closes)-

private String putDotBeforeFileName(File file) {
    String fileName = file.getName();
    String fullPath = file.getAbsolutePath();
    int indexOfDot = fullPath.indexOf(".");
    String myRequiredFileName = "";
    if (indexOfDot == 0 && fileName.length() > 1) {
        myRequiredFileName = file.getParent() + "/" + fileName.substring(1);
    }
    try {
        Runtime.getRuntime().exec(
                "mv " + file.getAbsolutePath() + " " + myRequiredFileName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return myRequiredFileName;
}
patrecia
  • 29
  • 4

1 Answers1

1

Try this code

private String removeDotBeforeFileName(File file) {
        String fileName = file.getName();
        String fullPath = file.getAbsolutePath();
        String myRequiredFileName = "";
        if (fileName.length() > 1 && fullPath.charAt(0)=='.') {
            myRequiredFileName = file.getParent() + "/" + fileName.substring(1);
           file.renameTo(new File(myRequiredFileName));
        }

        return myRequiredFileName;
    }
Darish
  • 11,032
  • 5
  • 50
  • 70