java如何去掉后缀名???

acai9527 2009-03-26 08:17:05
File file=new File("d:\\test");
String [] fileNames = file.list(); //这里取到的是文件名+后缀名。这里能否只取文件名,不要后缀名??
for(int i=0;i<fileNames.length;i++){
System.out.println(fileNames[i]);
}


例如:test文件夹下有以下这些文件(注:有多后缀名的文件):
aa.htm , bb.html , cc.txt.mht , dd.java

问题:如何去掉后缀名???
...全文
4173 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
MRLIYUANWEN 2012-09-06
  • 打赏
  • 举报
回复
String[] file = { "merge1.pdf", "xitong.html","test.jpg" };
for (int k = 0; k < file.length; k++) {
if (file != null) {
int i = file[k].lastIndexOf(".");
if (i > 0 && i < file[k].length() - 1) {
System.out.println(file[k].substring(0, i));
}
}
}
steryzone 2009-03-27
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 jourqel 的回复:]
可以考虑用split~用它来截取字符串~获取.以前的文件名~
示例(通过判断空格截取):
public class SplitDemo {

public static String[] ss = new String[20];

public SplitDemo() {

String s = "The rain in Spain falls mainly in the plain.";
// 在每个空格字符处进行分解。
ss = s.split(" ");
}

public static void main(String[] args) {


[/Quote]
用spilt是可以,但是比较麻烦吧,呵呵,因为你用spilt分割后还有去筛选呢,呵呵。。。
还是用lastindexof好
hoojo 2009-03-26
  • 打赏
  • 举报
回复
lastIndexOf(".") 最后的一个. 肯定没有问题
acai9527 2009-03-26
  • 打赏
  • 举报
回复
有的文件不只一个“.”



我回去试试先
Defonds 2009-03-26
  • 打赏
  • 举报
回复
String ext = fileNames[i].substring(f_name.lastIndexOf(".") + 1, f_name.length());//后缀名得到,后缀名长度也得到
然后用substring(*,*)方法得到没后缀名的文件名
hoojo 2009-03-26
  • 打赏
  • 举报
回复

String filename = file.getFileName();
String name = filename.substring(0,filename.lastIndexOf("."));//这个是获取除后缀疑问的名称(你要的)
//filename.substring(filename.lastIndexOf("."));//这个是获取后缀名


兄弟 够意思吧
希望没有错哦
^_*
Defonds 2009-03-26
  • 打赏
  • 举报
回复
String ext = fileNames[i].lastIndexOf(".");//后缀名
然后用substring(*,*)方法得到没后缀名的文件名
jourqel 2009-03-26
  • 打赏
  • 举报
回复
可以考虑用split~用它来截取字符串~获取.以前的文件名~
示例(通过判断空格截取):
public class SplitDemo {

public static String[] ss = new String[20];

public SplitDemo() {

String s = "The rain in Spain falls mainly in the plain.";
// 在每个空格字符处进行分解。
ss = s.split(" ");
}

public static void main(String[] args) {

SplitDemo demo = new SplitDemo();
for (int i = 0; i < ss.length; i++)
System.out.println(ss[i]);
}

}

程序结果:
The
rain
in
Spain
falls
mainly
in
the
plain.
palm_civet 2009-03-26
  • 打赏
  • 举报
回复
String类里面有方法可以找到最后一个 "." 的位置,好像是lastindexof,自己查下吧,然后截取这个位置之前所有的字符就是了
acai9527 2009-03-26
  • 打赏
  • 举报
回复
方法不只一种吧,越简单越好 先谢了

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧