java实现给复制的文件自动重命名

在Java中实现给复制的文件自动重命名,可以按以下步骤进行操作:

  1. 获取源文件的名称和路径。
String sourceFileName = "源文件路径";
File sourceFile = new File(sourceFileName);
String sourceFilePath = sourceFile.getParent();
String sourceFileExtension = sourceFileName.substring(sourceFileName.lastIndexOf("."));
  1. 生成新的文件名。可以使用UUID类来生成一个唯一的文件名,也可以根据需要自己定义新的文件名规则。
String newFileName = UUID.randomUUID().toString() + sourceFileExtension;
  1. 创建新的文件对象,指定新的文件名和路径。
String newFilePath = sourceFilePath + File.separator + newFileName;
File newFile = new File(newFilePath);
  1. 复制源文件到新文件。
Files.copy(sourceFile.toPath(), newFile.toPath());

完整的代码示例:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;
public class FileCopyWithAutoRename {
    public static void main(String[] args) {
        String sourceFileName = "源文件路径";
        File sourceFile = new File(sourceFileName);
        String sourceFilePath = sourceFile.getParent();
        String sourceFileExtension = sourceFileName.substring(sourceFileName.lastIndexOf("."));
        
        String newFileName = UUID.randomUUID().toString() + sourceFileExtension;
        String newFilePath = sourceFilePath + File.separator + newFileName;
        File newFile = new File(newFilePath);
        
        try {
            Files.copy(sourceFile.toPath(), newFile.toPath());
            System.out.println("文件复制成功");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件复制失败");
        }
    }
}

以上代码中的"源文件路径"需要根据实际情况进行修改,指定要复制的源文件的路径。复制完成后,新文件将保存在与源文件相同的目录下,并且自动重命名为一个唯一的文件名。

 
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定