【问题标题】:Create files with same name without overwriting java创建同名文件而不覆盖java
【发布时间】:2016-03-17 06:18:37
【问题描述】:

我以前见过这个问题,但我无法从建议中找到解决方案。我需要能够创建一个具有相同名称的文件而不覆盖旧文件。例如,如果我有 images.txt,如果我尝试创建另一个同名文件,它应该是 images(1).txt, images(2).txt 等等。到目前为止,我只能创建第一个索引。这是我的代码:

public class Filenames {

    public static void main(String[] args) throws IOException {
        String filename = "images.txt";
        File f = new File(getNewFileName(filename));
        f.createNewFile();

    }

    public static String getFileExtension(String filename) {
        return filename.substring(filename.lastIndexOf("."));
    }

    public static String getNewFileName(String filename) throws IOException {
        File aFile = new File(filename);
        int fileNo = 0;
        String newFileName = "";
        if (aFile.exists() && !aFile.isDirectory()) {
            fileNo++;
            newFileName = filename.replaceAll(getFileExtension(filename), "(" + fileNo + ")" + getFileExtension(filename));
        } else if (!aFile.exists()) {
            aFile.createNewFile();
            newFileName = filename;
        }
        return newFileName;
    }
}

我错过了什么?

【问题讨论】:

    标签: java file filenames


    【解决方案1】:

    试试这个,请验证

    public static String getNewFileName(String filename) throws IOException {
        File aFile = new File(filename);
        int fileNo = 0;
        String newFileName = "";
        if (aFile.exists() && !aFile.isDirectory()) {
    
    
            //newFileName = filename.replaceAll(getFileExtension(filename), "(" + fileNo + ")" + getFileExtension(filename));
    
            while(aFile.exists()){
                fileNo++;
                aFile = new File("images(" + fileNo + ").txt");
                newFileName = "images(" + fileNo + ").txt";
            }
    
    
        } else if (!aFile.exists()) {
            aFile.createNewFile();
            newFileName = filename;
        }
        return newFileName;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 2015-06-20
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多