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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值