//org.apache.commons.io Class FileUtils:
//通常用来复制文件,将文件复制到当前目录下,和复制到非当前目录时,会有细微的变化
//1. 复制到当前目录下:
String imgPath = "D:\\test\\jpg111.jpg";
String copyImgPath = "D:\\test\\Fighter.jpg";
File img = new File(imgPath);
File copyOfImg = new File(copyImgPath);
// 如果源文件存在的话,不再需要判断,复制文件的目录是否存在;
// 其实,还是应该判断下源文件是否存在
if(!img.exists() || !img.isFile()) {
System.out.println("该文件不存在");
} else {
//存在则进行复制
FileInputStream imgIS = new FileInputStream(img);
BufferedInputStream uis = new BufferedInputStream(imgIS);
FileOutputStream copyImgOut = new FileOutputStream(copyOfImg);
byte[] bytes = new byte[1024];
int ch = 0;
while((ch = imgIS.read(bytes, 0, 1024))!=-1) {
copyImgOut.write(bytes, 0, ch);
}
}
//2. 复制到非当前目录下:
//则需要对复制文件目录是否存在进行判断,不存在则创建
if(!copyOfImg.exists() || !copyOfImg.isDirectory()) {
copyOfImg.createNewFile();
}
//3.若复制文件已经存在,则会将其改写为,当前的源文件。
//注意:创建一个文件,若目录不存在,则在复制文件的时候,会找不到该文件的路径
// 通常在,例如,File file = new File("C:\\path1\\path2\\filename.extention");
// 的时候,要用 file.getParentFile() 来获取路径是否存在,不存在,则创建
// file.getParentFile().mkdirs();
// 然后, FileInputStream(file); 就可以读取了