文件名后面补时间:
public static void initFile(String sPath) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS");// 设置日期格式 String sTime = df.format(new Date()); File f = new File(sPath); if (!f.exists()) { return; } else { String sExtension = sPath.substring(sPath.lastIndexOf(".")); String sFilePath_without_ext = sPath.substring(0, sPath.lastIndexOf(".")); String sNewName = sFilePath_without_ext + sTime + sExtension; f.renameTo(new File(sNewName)); } }
D:\\user_kn.txt
→
D:\\user_kn2017-04-09_18-19-40-549.txt
文件名前面补时间:
public static void initFile(String sPath) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS");// 设置日期格式 String sTime = df.format(new Date()); File f = new File(sPath); if (!f.exists()) { return; } else { // 文件夹路径(盘符有\,普通文件夹没有) String sDir = f.getParent(); // 文件名 String sName = f.getName(); // 新文件名 String sNewName = sDir + "\\" + sTime + "@" + sName; f.renameTo(new File(sNewName)); System.out.println(sNewName); } }
D:\\user_kn.txt
→
D:\\2017-04-09_18-45-22-297@user_kn.txt