如果文件存在,如何增加文件名

时间:2016-12-24 14:37:29

标签: java android

如果文件已经存在,如何增加文件名? 这是我正在使用的代码 -

else if (d > 0) { /* Insert d items */
    k = Py_SIZE(a);
    if (list_resize(a, k+d) < 0)
        goto Error;
    item = a->ob_item;
    memmove(&item[ihigh+d], &item[ihigh],
        (k - ihigh)*sizeof(PyObject *));
}
for (k = 0; k < n; k++, ilow++) {
    PyObject *w = vitem[k];
    Py_XINCREF(w);
    item[ilow] = w;
}

此代码有效,但只保存了2个文件,如file.jpg和file2.jpg

8 个答案:

答案 0 :(得分:7)

此问题始终是初始化num = 0,因此如果file存在,则保存file0.jpg而不检查file0.jpg是否存在? 所以,编码工作。您应该检查直到可用:

int num = 0;
String save = at.getText().toString() + ".jpg";
File file = new File(myDir, save);
while(file.exists()) {
    save = at.getText().toString() + (num++) +".jpg";
    file = new File(myDir, save); 
}

答案 1 :(得分:1)

试试这个:

File file = new File(myDir, at.getText().toString() + ".jpg"); 

for (int num = 0; file.exists(); num++) {
    file = new File(myDir, at.getText().toString() + num + ".jpg");
}

// Now save/use your file here

答案 2 :(得分:0)

int i = 0;
String save = at.getText().toString();
String filename = save +".jpg";
File f = new File(filename);
while (f.exists()) {
    i++;
    filename =save+ Integer.toString(i)+".jpg";
    f = new File(filename);
}
f.createNewFile();

答案 3 :(得分:0)

此函数返回具有所有扩展名的编号完全为新的文件

对其他人有帮助..

private File getFileName(File file) {
        if (file.exists()){
            String newFileName = file.getName();
            String simpleName = file.getName().substring(0,newFileName.indexOf("."));
            String strDigit="";

            try {
                simpleName = (Integer.parseInt(simpleName)+1+"");
                File newFile = new File(file.getParent()+"/"+simpleName+getExtension(file.getName()));
                return getFileName(newFile);
            }catch (Exception e){}

            for (int i=simpleName.length()-1;i>=0;i--){
                if (!Character.isDigit(simpleName.charAt(i))){
                    strDigit = simpleName.substring(i+1);
                    simpleName = simpleName.substring(0,i+1);
                    break;
                }
            }

            if (strDigit.length()>0){
                simpleName = simpleName+(Integer.parseInt(strDigit)+1);
            }else {
                simpleName+="1";
            }

            File newFile = new File(file.getParent()+"/"+simpleName+getExtension(file.getName()));
            return getFileName(newFile);
        }
        return file;
    }

private String getExtension(String name) {
        return name.substring(name.lastIndexOf("."));
}

答案 4 :(得分:0)

通过使用do while循环,您可以避免此处某些答案的代码重复

下面是使用Java 7中引入的更新的NIO Path API的示例

Path candidate = null;
int counter = 0;
do {
    candidate = Paths.get(String.format("%s-%d",
            path.toString(), ++counter));
} while (Files.exists(candidate));
Files.createFile(candidate);

答案 5 :(得分:0)

@Tejas Trivedi的答案需要用我自己的代码解决此问题,因此当您多次下载同一文件时,它就像Windows一样工作

// This function will iteratively to find a unique file name to use when given a file: example (###).txt
//  More or less how windows will save a new file when one already exists example.txt becomes example (1).txt
//  if example.txt already exists
private File getUniqueFileName(File file) {
    File originalFile = file;
    try {
        while (file.exists()) {
            String newFileName = file.getName();
            String baseName = newFileName.substring(0, newFileName.lastIndexOf("."));
            String extension = getExtension(newFileName);

            Pattern pattern = Pattern.compile("( \\(\\d+\\))\\."); // Find ' (###).' in the file name, if it exists
            Matcher matcher = pattern.matcher(newFileName);

            String strDigits = "";
            if (matcher.find()) {
                baseName = baseName.substring(0, matcher.start(0)); // remove the (###)
                strDigits = matcher.group(0); // grab the ### we'll want to increment
                strDigits = strDigits.substring(strDigits.indexOf("(") + 1, strDigits.lastIndexOf(")")); // strip off the ' (' and ').' from the match
                // increment the found digit and convert it back to a string
                int count = Integer.parseInt(strDigits);
                strDigits = Integer.toString(count + 1);
            } else {
                strDigits = "1"; // if there is no (###) match then start with 1
            }
            file = new File(file.getParent() + "/" + baseName + " (" + strDigits + ")" + extension); // put the pieces back together
        }
        return file;
    } catch (Error e) {
        return originalFile; // Just overwrite the original file at this point...
    }

}

private String getExtension(String name) {
    return name.substring(name.lastIndexOf("."));
}

在“ example.txt”已经存在时调用getUniqueFileName(new File('/dir/example.txt'),同时生成一个以“ / dir / example(1).txt”为目标的新文件,如果该文件也存在,它将保持括号之间的数字递增,直到出现找到唯一的文件,如果发生错误,它将仅提供原始文件名。

我希望这对需要在Android或其他平台上用Java生成唯一文件的人有所帮助。

答案 6 :(得分:0)

除了第一个答案,我还做了一些其他更改

private File getUniqueFileName(String folderName, String searchedFilename) {
        int num = 1;
        String extension = getExtension(searchedFilename);
        String filename = searchedFilename.substring(0, searchedFilename.lastIndexOf("."));
        File file = new File(folderName, searchedFilename);
        while (file.exists()) {
            searchedFilename = filename + "("+(num++)+")"+extension;
            file = new File(folderName, searchedFilename);
        }
        return file;
    }

答案 7 :(得分:0)

Kotlin 版本:

private fun checkAndRenameIfExists(name: String): File {
    var filename = name
    val extension = "pdf"
    val root = Environment.getExternalStorageDirectory().absolutePath
    var file = File(root, "$filename.$extension")
    var n = 0
    while (file.exists()) {
        n += 1
        filename = "$name($n)"
        file = File(root, appDirectoryName + File.separator + "$filename.$extension")
    }
    return file
}