代码之家  ›  专栏  ›  技术社区  ›  Darshan

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

  •  8
  • Darshan  · 技术社区  · 9 年前

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

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

    这段代码可以工作,但只有2个文件像文件一样保存。jpg和file2.jpg

    10 回复  |  直到 9 年前
        1
  •  24
  •   nartoan    9 年前

    这个问题总是初始化的 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); 
    }
    
        2
  •  1
  •   Kamran Ahmed    9 年前

    试试这个:

    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
    
        3
  •  1
  •   Bibin Baby    5 年前

    除了第一个答案,我还做了一些修改

    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;
        }
    
        4
  •  0
  •   Ahmad Aghazadeh    9 年前
    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();
    
        5
  •  0
  •   svarog Rostyslav    6 年前

    您可以使用 do while

    下面是一个使用Java 7中引入的新NIO路径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);
    
        6
  •  0
  •   cpuchip    5 年前

    @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("."));
    }
    

    使命感 getUniqueFileName(new File('/dir/example.txt') “当”是一个例子。生成新文件时,txt已存在,目标为“/dir/example(1)”。txt'如果它也存在,它会一直递增括号之间的数字,直到找到唯一的文件,如果发生错误,它只会给出原始文件名。

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

        7
  •  0
  •   hardik parmar    4 年前

    科特林版本:

    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
    }
    
        8
  •  0
  •   JulienH    4 年前

    这是我用来处理这个案例的解决方案。适用于文件夹和文件。

    var destination = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyFolder")
     if (!destination.exists()){
         destination.mkdirs()
     } else {
         val numberOfFileAlreadyExist =
             destination.listFiles().filter { it.name.startsWith("MyFolder") }.size
         destination = File(
             Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
             "MyFolder(${numberOfFileAlreadyExist + 1})"
         )
         destination.mkdirs()
     }
    

    祝你今天愉快!

        9
  •  0
  •   asbachb SankarRaman    3 年前

    另一个简单的逻辑解决方案是使用apachecommons.IO获取目录下的唯一文件名 WildcardFileFilter 要匹配文件名并获取给定名称的存在数量,请递增计数器。

    public static String getUniqueFileName(String directory, String fileName){
      String fName = fileName.substring(0, fileName.lastIndexOf("."));
      Collection<File> listFiles = FileUtils.listFiles(new File(directory), new WildcardFileFilter(fName+"*", IOCase.INSENSITIVE), DirectoryFileFilter.DIRECTORY);
      if(listFiles.isEmpty()){
        return fName;
      }
      return fName.concat(" ("+listFiles.size()+")");
    }
    
        10
  •  -1
  •   Tejas Trivedi    6 年前

    帮助别人。。

    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("."));
    }