/**
* 轉移文件路徑
*
* @param filename
* 文件名
* @param oldpath
* 舊文件路徑
* @param newpath
* 新文件路徑
* @param cover
* 若新目錄下存在和轉移文件具有相同文件名的文件時,是否覆蓋新目錄下文件,cover=true將會覆蓋原文件,否則不操作
*/
public void changeDirectory(String fileName, String oldPath,
String newPath, boolean cover) {
if (!oldPath.equals(newPath)) {
File oldFile = new File(oldPath + "/" + fileName);
File newFile = new File(newPath + "/" + fileName);
if (newFile.exists()) {
if (cover) {
newFile.delete();
oldFile.renameTo(newFile);
} else {
System.out.println("新目錄已經存在:" + fileName);
}
} else {
oldFile.renameTo(newFile);
}
}
}
/**
* 文件重命名
*
* @param path
* 文件目錄
* @param oldname
* 原來的文件名
* @param newname
* 新文件名
*/
public void renameFile(String path, String oldname, String newname) {
if (!oldname.equals(newname)) {
File oldfile = new File(path + "/" + oldname);
File newfile = new File(path + "/" + newname);
if (newfile.exists()) {// 若在該目錄下已經有一個文件和新文件名相同,則刪除重建
System.out.println(newname + "已經存在!");
newfile.delete();
oldfile.renameTo(newfile);
} else {
oldfile.renameTo(newfile);
}
}
}
/**
* 創建文件夾
*
* @param path
* 文件路徑
*/
public void createDir(String path) {
String pathes[] = path.split("/");
String filePath = "";
for (int i = 0; i < pathes.length; i++) {
filePath += pathes[i];
filePath += "/";
File dirPath = new File(filePath);
if (!dirPath.exists())
dirPath.mkdir();
}
}