Java給文件重命名


直接上代碼:

/** 文件重命名
	 * @param path
	 *            文件路徑
	 * @param oldname
	 *            原有的文件名
	 * @param newname
	 *            新的文件名
	 */
	public static boolean renameFile(String path, String oldname, String newname) {
		if (!oldname.equals(newname)) {// 新的文件名和以前文件名不同時,纔有必要進行重命名
			File oldfile = new File(path + "/" + oldname);
			File newfile = new File(path + "/" + newname);
			if (!oldfile.exists()) {
				log.error("需要重命名的文件不存在");
				return false;// 重命名文件不存在
			}
			if (newfile.exists()) {// 若在該目錄下已經有一個文件和新文件名相同,則不允許重命名
				log.error(newname + "已經存在!");
				return false;
			} else {
				boolean isSuccess = oldfile.renameTo(newfile);
				return isSuccess;
			}
		} else {
			log.error("新文件名和舊文件名相同...");
		}
		return false;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章