Add index to filename for existing file (file.txt => file_1.txt)

后端 未结 4 778
孤城傲影
孤城傲影 2021-01-23 05:18

I want to add an index to a filename if the file already exists, so that I don\'t overwrite it.

Like if I have a file myfile.txt and same time myfile.

4条回答
  •  一生所求
    2021-01-23 05:52

    Using commons-io:

    private static File getUniqueFilename( File file )
    {
        String baseName = FilenameUtils.getBaseName( file.getName() );
        String extension = FilenameUtils.getExtension( file.getName() );
        int counter = 1
        while(file.exists())
        {
            file = new File( file.getParent(), baseName + "-" + (counter++) + "." + extension );
        }
        return file
    }
    

    This will check if for instance file.txt exist and will return file-1.txt

提交回复
热议问题