A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 原子弹 中级黑马   /  2014-3-26 01:48  /  1434 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

编写一个可以获取文件扩展名的函数,形参接受一个文件名字符串,
                  返回一个扩展名字符串
      请求大神指点迷津:'(

评分

参与人数 1技术分 +1 收起 理由
朱神必 + 1

查看全部评分

5 个回复

倒序浏览
本帖最后由 lwy0319 于 2014-3-26 03:45 编辑

文件名字而已,只是字符串的处理罢了,跟文件本身的操作没什么关系,记得扩展名的标志是".",代码如下:public class Text {
        public static void main(String[] args){
                String str="demo.txt";
                System.out.println(fun(str));
        }
        static String fun(String str){
                char chr[]=str.toCharArray();//将接收的代表文件名字的字符串转换为字符数组
                int a=0;//String类型构造函数中的起始值
                for(int i=0;i<chr.length;i++){//循环检索字符数组的脚标
                        if(chr=='.'){
                                a=i;//将.的位置作为起始值
                        }
                }
                return new String(chr,a,chr.length-a);
                //将字符数组中从"."的位置开始向右数,数到字符数组的总长减去从左起点到"."那么长的位置的字符转换成字符串并返回
        }
}


评分

参与人数 1技术分 +1 收起 理由
朱神必 + 1

查看全部评分

回复 使用道具 举报
    public static void main(String[] args) {
      
            String ss="asdfsdf.ccc";
        System.out.println(        getExtendFileName(ss));
    }
        private static String getExtendFileName(String ss) {
               
                //lastIndexOf('.')获得.最后出的位置,因是扩展名所以substring从lastIndexOf('.')+1
                //截取
                return ss.substring(ss.lastIndexOf('.')+1);
        }

评分

参与人数 1技术分 +1 收起 理由
朱神必 + 1

查看全部评分

回复 使用道具 举报
package test;
import java.io.*;
import java.util.*;
public class Seven3 {
public static void main(String[] args)throws  Exception{
File file=new File("D:\\me.txt");
getName(file);
}
public static void getName(File file)
{
String name=file.getName();
String tz=name.substring(name.lastIndexOf(".")+1);
System.out.println("文件名为"+name+"拓展名为:"+tz);
}
}
回复 使用道具 举报
类是具有相同数据结构(属性)和相同操作功能(行为)对象的集合。对象就是符合某种类所产生的一个实例。对象与类的关系是: 对象的共性抽象为类,类的实例化就是对象。 对象的声明: 类名 对象名=new 类名(); 对象的调用: 访问属性:对象名.属性名; 访问方法:对象名.方法名();
回复 使用道具 举报
public static String getFileExtensionName(String fileName) { // 根据题目要求 需要创建一个返回值类型为String// 接收数据类型为String的方法// 由于我在该类中需要通过主方法运行,所以方法前我加了static。
        if (fileName != null && fileName.contains(".")) { // 首先判断传入的字符串是否为空,同时也要判断是否含有字符串"."。
        return fileName.substring(fileName.lastIndexOf(".") + 1); // 这一步是字符串子串的获取,以及从什么地方开始获取。同时要注意后缀名是最后一个点以后的内容。
                }
                return "文件名输入有误";
        }

        public static void main(String[] args) {
                String fileName = "ithemai.com";

                String fileExtensionName = getFileExtensionName(fileName); // 调用方法。

                System.out.println(fileExtensionName);
        }

}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马