java:重命名文件并添加后缀(如果已存在)

问题描述 投票:0回答:1

我需要重命名文件。

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

问题是,当我尝试“重命名”文件时,它可能已经存在了。

有没有按照惯例添加像

-number
这样的后缀来解决它?

比如我需要重命名为

newfile
并且
newfile
newfile1
存在,我想重命名为
rename2
.

如果在重命名

newfile2
文件时,另一个文件被重命名为
newfile2
那么
newfile3
应该写...

有什么想法吗?

java java-io java-nio
1个回答
0
投票

源文件可以移动到目标目录(targetDir),当文件名已经存在于目标目录中时,将重命名文件。虽然没有经过彻底测试。

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;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.