java复制文件并重命名
时间: 2023-11-10 12:52:29 浏览: 47
可以使用Java的File类来实现文件的复制和重命名操作。首先,你需要创建一个新的文件夹B,如果它不存在的话。然后,你可以使用File类的renameTo()方法将图片A复制到新文件夹B并重命名。下面是一个示例代码:
```
import java.io.File;
import java.io.IOException;
public class FileCopyRenameExample {
public static void main(String[] args) {
String sourceFilePath = "/Users/mgx/apache-tomcat-8.5.78/webapps/img/testimg.jpg";
String destinationFolderPath = "/Users/mgx/apache-tomcat-8.5.78/webapps/img/newfolder";
String newFileName = "newimg.jpg";
File sourceFile = new File(sourceFilePath);
File destinationFolder = new File(destinationFolderPath);
File destinationFile = new File(destinationFolder, newFileName);
// 创建新文件夹B
if (!destinationFolder.exists()) {
destinationFolder.mkdirs();
}
try {
// 复制并重命名文件
sourceFile.renameTo(destinationFile);
System.out.println("文件复制并重命名成功!");
} catch (Exception e) {
System.out.println("文件复制并重命名失败:" + e.getMessage());
}
}
}
```
请注意,上述代码中的路径和文件名需要根据你的实际情况进行更改。你可以把源文件路径(sourceFilePath)、目标文件夹路径(destinationFolderPath)和新文件名(newFileName)替换为你自己的路径和文件名。