java对文件目录的copy、删除操作,常放在工具类里面
/**
* copy单个文件
*
* @param oldFilePath
* @param newFilePath
* @return
*/
public static int copyFile(String oldFilePath, String newFilePath) {
int byteSum = 0;
int byteRead = 0;
File oldFile = new File(oldFilePath);
if (oldFile.exists()) {
InputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(oldFilePath);
out = new FileOutputStream(newFilePath);
byte[] buffer = new byte[2048];
while ((byteRead = in.read(buffer)) != -1) {
byteSum += byteRead;
out.write(buffer, 0, byteRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.flush();
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return byteSum;
}
/**
* copy整个目录
*
* @param oldFilePath
* @param newFilePath
*/
public static void copyDirectory(String oldFilePath, String newFilePath) {
File newFile = new File(newFilePath);
File oldFile = new File(oldFilePath);
if (oldFile.isDirectory() && !newFile.isDirectory()) {
newFile.mkdir();
}
String[] files = oldFile.list();
File tmp = null;
String tmpPath = null;
String newTmpPath = null;
for (int i = 0; i < files.length; i++) {
if (oldFilePath.endsWith(File.separator)) {
tmpPath = oldFilePath + files[i];
} else {
tmpPath = oldFilePath + File.separator + files[i];
}
tmp = new File(tmpPath);
String seprator = newFilePath.endsWith(File.separator) ? ""
: File.separator;
newTmpPath = newFilePath + seprator + files[i];
if (tmp.isFile()) {
copyFile(tmpPath, newTmpPath);
} else if (tmp.isDirectory()) {
copyDirectory(tmpPath, newTmpPath);
}
}
}
/**
* 删除整个目录
*
* @param path
*/
public static void delDiectory(String path) {
File file = new File(path);
if (file.isFile()) {
file.delete();
return;
}
if (!file.isDirectory())
return;
String[] tmp = file.list();
String newpath = null;
for (int i = 0; i < tmp.length; i++) {
if (path.endsWith(File.separator)) {
newpath = path + tmp[i];
} else {
newpath = path + File.separator + tmp[i];
}
File tmpFile = new File(newpath);
if (tmpFile.isFile()) {
tmpFile.delete();
} else if (tmpFile.isDirectory()) {
delDiectory(newpath);
tmpFile.delete();
}
}
new File(path).delete();
}