java: rename file and add suffix if it already exists

423 views Asked by At

I need to rename a file.

Path destPath = Paths.get(directoryPath, hash);
Files.move(path, destPath);

The problem is that when I'm trying to "rename" the file, it can already exist.

Is there anyway to solve it by convention adding a suffix like -number?

For example, if I need to rename to newfile and newfile and newfile1 exist, I want to rename to rename2.

If at the time to rename newfile2 file, another file is renamed to newfile2 then newfile3 should be written...

Any ideas?

1

There are 1 answers

3
vaultboy On

A source file can be moved to a target directory (targetDir) and will rename the file when the filename already exists in the target directory. Not thoroughly tested though.

package testcode;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class TestCode {

    public static void main(String[] args) {
        
        String dir = "C:"+File.separator+"Users"+File.separator+"Name"+File.separator+"Documents"+File.separator;
        String fileName = "filename.ext";
        String fileLocation = dir+fileName;
        Path source = Paths.get(fileLocation);
        String targetDir = source.getParent().toString();        
        
        moveFile(source, targetDir);
    }
       
    private static boolean moveFile(Path source, String targetDir) {
        
        String fileName = removeExtension(source.getFileName().toString());
        String ext = getFileExtension(source.getFileName().toString());

        String target = targetDir+File.separator+fileName+ext;     
        int count = 1;
        
        while (Files.exists(Paths.get(target))) {
            target = targetDir+File.separator+fileName+count+ext;     
            count++;
        }
            
        try {             
            Files.move(source, Paths.get(target));
            System.out.print("Moved file");
            return true;                
        } 
        catch (Exception e) {
            e.printStackTrace();
        }  
         
        return false;
    }
    
    private static String getFileExtension(String fileName) {
        int index = fileName.lastIndexOf('.');
        if (index > 0) {
            return fileName.substring(index);
        }
        return null;
    }
    
    private static String removeExtension(String fileName) {
        int index = fileName.lastIndexOf('.');
        if (index > 0) {
            return fileName.substring(0, index);
        }       
        return null;
    }

}