java文件重命名
——不要去追一匹马,用追马的时间种草,待到春暖花开时,会有一群骏马任你挑选;不要刻意去讨好一个人,用讨好别人的时间,提升自己的能力,待到时机成熟时,会有一大批的朋友与你同行。所以,丰富自己比取悦他人更有力量。
import java.io.File;
/**
* 文件重命名
*
* 2016年3月26日 上午11:06:15
*/
public class FileRenameUtil {
public static void main(String[] args) {
File f = new File("a.txt");
File f2 = new File("b.txt");
boolean b = f.renameTo(f2);
System.out.println("重命名结果:"+b);
}
/**
* 如果存在同名文件,重命名会返回false
* @param oldName
* @param newName
* @return
*/
public static boolean rename(String oldName, String newName){
boolean b = false;
try {
File oldFile = new File(oldName);
File newFile = new File(newName);
b = oldFile.renameTo(newFile);
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
/**
* @param pathDir 文件所在路径
* @param oldName
* @param newName
* @return
*/
public static boolean rename(String pathDir, String oldName, String newName) {
boolean b = false; // 文件重命名是否成功
try {
File oldFile = new File(pathDir, oldName);
File newFile = new File(pathDir, newName);
b = oldFile.renameTo(newFile);
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
/**
* @param oldFile
* @param newFileName
* @throws Exception
*/
@Deprecated
public static void rename2(String oldFile,String newFileName) {
File old = new File(oldFile);
try {
// 检查文件是否存在
checkFile(old);
// 文件所在路径
String pathDir = getFileParentPath(old);
File newFile = new File(pathDir,newFileName);
if(newFile.exists()){
throw new Exception("已存在同名文件,不能重命名!");
}
if(old.isAbsolute()){
old.renameTo(newFile);
}else{
File tempF = new File(pathDir,old.getName());
tempF.renameTo(newFile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件的父路径
* @param file
* @return
* @throws Exception
*/
private static String getFileParentPath(File file) throws Exception{
if(file == null || !file.exists()){
throw new Exception("文件不存在,请检查!");
}
String path = file.getAbsolutePath();
int len = path.lastIndexOf("\\");
return path.substring(0,len);
}
/**
* @param f
* @throws Exception
*/
private static void checkFile(File f) throws Exception{
if(f==null){
throw new Exception("传入参数为空null");
}
if(!f.exists()){
throw new Exception("文件不存在,请检查!" + f.getAbsolutePath());
}
}
}
时间:2016年3月26日12:55:18

浙公网安备 33010602011771号