JAVA——将一个文件复制到另一个目录下
程序员文章站
2022-07-11 09:09:46
...
例如:将图片timg.jpg从D:/tupian目录,复制到D:/images目录,复制后的名称改为了timg2.jpg
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class aaa {
public static void main(String[] args) throws IOException {
String oldpath = "D:/tupian/timg.jpg";
String newpath = "D:/images/timg2.jpg";
copy(oldpath, newpath);
}
private static void copy(String oldpath, String newpath) throws IOException {
File oldpaths = new File(oldpath);
File newpaths = new File(newpath);
if (!newpaths.exists()) {
Files.copy(oldpaths.toPath(), newpaths.toPath());
} else {
newpaths.delete();
Files.copy(oldpaths.toPath(), newpaths.toPath());
}
}
}