下面的代码应该可以
[Java] 纯文本查看 复制代码 import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test3 {
String imageReg = "^[a-zA-Z0-9_]+(\\.jpeg|\\.gif|\\.png|\\.bmp|\\.tiff|\\.psd|\\.svg|\\.jpg)$";
public static void main(String[] args) {
Test3 test = new Test3();
test.copyimage("d://aaa");
}
public void copyimage(String path) {
File srcFile = new File(path);
String[] file = srcFile.list();
for (int i = 0; i < file.length; i++) {
File temp = new File(path + "/" + file[i]);
System.out.println(path + "/" + file[i]);
if (temp.isFile()) {
if (temp.getName().matches(imageReg)) {
String result = fileCopy(path + "/" + file[i], "D://a_cope");
System.out.println(result);
}
}
else
{
if (temp.isDirectory()) {
copyimage(path + "/" + file[i]);
System.out.println("我又执行一遍");
}
}
}
}
public static String fileCopy(String srcPath, String desPath) {
String result = "";
File old = new File(srcPath);
File newImage = new File(desPath);
newImage.mkdirs();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
if (!old.exists()) {
result = "the file is not exists";
return result;
} else {
fis = new FileInputStream(old);
if (!newImage.exists()) {
// newImage.mkdir();
newImage.createNewFile();
}
fos = new FileOutputStream(newImage + "/" + old.getName());
byte[] temp = new byte[1000];
int size = fis.read(temp);
while (size != -1) {
fos.write(temp);
size = fis.read(temp);
}
result = "the File Copy is success!";
return result;
}
} catch (FileNotFoundException fileNot) {
result = "the File Copy is Failed!";
fileNot.printStackTrace();
return result;
} catch (IOException e) {
e.printStackTrace();
result = "the File Copy is Failed!";
return result;
} finally {
try {
fis.close();
fos.close();
} catch (Exception ex) {
}
}
}
} |