由于平时需要,我们经常会去获取文件的扩展名或者不带扩展名的文件名,这主要用到java中String类中的SubString()方法与lastIndexOf()。
下面是具体的例子:
package tst;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/*获取文件的后缀名*/
public class Test{
public static void main(String args[]){
File f =new File("VIP客户资料.java");
String fileName=f.getName();
String prefix=fileName.substring(fileName.lastIndexOf("."));//如果想获得不带点的后缀,变为fileName.lastIndexOf(".")+1
int num=prefix.length();//得到后缀名长度
String fileOtherName=fileName.substring(0, fileName.length()-num);//得到文件名。去掉了后缀
String Date = getCurrentDate();
String Time =getCurrentTime().replaceAll(":", ":");
/*构造出含有时间的文件名,eg:VIP客户资料_2014-08-12-11_11:14:25*/
fileName=fileName.substring(0, fileName.length()-num)+"_"+Date+"_"+Time+prefix;
//打印相应名字
System.out.println(prefix+" length:"+num);
System.out.println(fileOtherName);
System.out.println(fileName);
}
/**
* 得到当前系统日期
*
* @return 当前时间的格式字符串,格式为"yyyy—mm-dd"
*/
public static String getCurrentDate() {
String pattern = "yyyy-MM-dd";
SimpleDateFormat df = new SimpleDateFormat(pattern);
Date today = new Date();
String tString = df.format(today);
return tString;
}
/**
* 得到当前系统时间
*
* @return 当前时间的格式字符串,时间格式为"HH:mm:ss"
*/
public static String getCurrentTime() {
String pattern = "HH:mm:ss";
SimpleDateFormat df = new SimpleDateFormat(pattern);
Date today = new Date();
String tString = df.format(today);
return tString;
}
}