java图片复制并改名
时间: 2023-09-14 15:03:07 浏览: 51
你可以使用Java的IO类库来复制并改名图片。以下是一个简单的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageCopyAndRename {
public static void main(String[] args) {
String sourcePath = "path/to/source/image.jpg"; // 原始图片路径
String targetPath = "path/to/target/image.jpg"; // 目标图片路径
try (FileInputStream fis = new FileInputStream(new File(sourcePath));
FileOutputStream fos = new FileOutputStream(new File(targetPath))) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
File targetFile = new File(targetPath);
String newFileName = "new_image_name.jpg";
File renamedFile = new File(targetFile.getParentFile(), newFileName);
if (targetFile.renameTo(renamedFile)) {
System.out.println("图片复制并改名成功!");
} else {
System.out.println("图片复制并改名失败!");
}
}
}
```
在这个示例代码中,我们首先使用FileInputStream和FileOutputStream来复制原始图片。然后,我们使用File类的renameTo()方法来改名目标文件。注意,我们首先创建一个新的File对象,它是目标文件的父文件夹和新文件名的组合,然后使用renameTo()方法将目标文件重命名为新的文件名。
当运行这段代码时,请确保将sourcePath和targetPath替换为您自己的路径,以及将newFileName替换为您想要的新文件名。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)