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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© adamjy 中级黑马   /  2014-4-21 22:20  /  857 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 adamjy 于 2014-4-22 12:39 编辑

请问以下代码,为什么得不到文件的扩展名?

  1. public static void main(String[] args) throws Exception {
  2.         //文件名为fileName
  3.         String fileName = "test.java.txt";
  4.         //打印文件扩展名
  5.         System.out.println(getExtension(fileName));               
  6. }
  7.         
  8. public static String getExtension(String fileName){
  9.         String[] strs = fileName.split(".");
  10.         return strs[strs.length-1];
  11. }
复制代码

5 个回复

倒序浏览

public static String getExtension(String fileName){
        String[] strs = fileName.split(".");  //点在java中代表任意字符.这是正则表达式.你可以改成这样("\\.")就可以了
        return strs[strs.length-1];
}
这个题可以这样做更好点,很好理解吧
public static String getName(String str) {
                int index = str.lastIndexOf(".");  //获取最后字符"."的位置
                String s = str.substring(index, str.length()); //根据获得的"."的角标来截取字符串到最后
                return s;
回复 使用道具 举报
"."在java中,有特殊的含义,在split方法里加[]就可以
  1. public static void main(String[] args) throws Exception {

  2.         //文件名为fileName

  3.         String fileName = "test.java.txt";

  4.         //打印文件扩展名

  5.         System.out.println(getExtension(fileName));               
  6. }

  7.         

  8. public static String getExtension(String fileName){

  9.         String[] strs = fileName.split("[.]");//这样

  10.         return strs[strs.length-1];

  11. }
复制代码
回复 使用道具 举报
这是根据正则表达式来拆解字符串,在正则表达式中.代表任何字符,所以需要用\\.来表示.
回复 使用道具 举报
package com.isoftstone.interview;

public class text2 {

        public static void main(String[] args) throws Exception {
                // 文件名为fileName
                String fileName = "test.java.txt";
                // 打印文件扩展名
                System.out.println(getExtension(fileName));
        }

        public static String getExtension(String fileName) {
                String[] strs = fileName.split("\\.");     \\ split("\\") 用法是这样的
                return strs[strs.length - 1];
        }
}
回复 使用道具 举报
⒈心只霸占沵 发表于 2014-4-21 22:29
"."在java中,有特殊的含义,在split方法里加[]就可以

还带这样啊 ???? 一直没注意 ,学习了。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马