java取得文件名不含后缀_③Java中获取文件扩展名以及文件名(不带扩展名)

由于平时需要,我们经常会去获取文件的扩展名或者不带扩展名的文件名,这主要用到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;

}

}


版权声明:本文为weixin_29009881原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。