当前位置: 移动技术网 > IT编程>开发语言>Java > 如何通过java获取文件名和扩展名

如何通过java获取文件名和扩展名

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了如何通过java获取文件名和扩展名,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

如:文件filepath = "e:\\test\\test.dxf"

1.获取文件名

eg:获取 test.dxf

通过file对象

import java.io.file;

public class test {
  public static void main(string[] args) {

    string filepath = "e:\\test\\test.dxf";
    file tmpfile=new file(filepath);
    string filename=tmpfile.getname();
    system.out.println(filename);
  }
}

使用split

public class test {
  public static void main(string[] args) {

    string filepath = "e:\\test\\test.dxf";
    //带扩展名的文件名
    string temp[] = filepath.split("\\\\");
    string filename = temp[temp.length - 1];
    system.out.println(filename);
  }
}

使用substring

public class test {
  public static void main(string[] args) {

    string filepath = "e:\\test\\test.dxf";
    string filename = filepath.substring(filepath.lastindexof("\\")+1);
    system.out.println(filename);
  }
}

2.获取不带扩展名的文件名

eg:获取 test

使用substring

public class test {
  public static void main(string[] args) {

    string filepath = "e:\\test\\test.dxf";
    string filename = filepath.substring(filepath.lastindexof("\\")+1);
    string name = filename.substring(0,filename.lastindexof("."));
    system.out.println(name);
  }
}


3.扩展名

eg:获取 dxf

使用substring

public class test {
  public static void main(string[] args) {

    string filepath = "e:\\test\\test.dxf";
    string filename = filepath.substring(filepath.lastindexof("\\")+1);
    string name = filename.substring(filepath.lastindexof(".")+1);
    system.out.println(name);
  }
}

public class test {
  public static void main(string[] args) {

    string filepath = "e:\\test\\test.dxf";
    string filename = filepath.substring(filepath.lastindexof("\\")+1);
    string[] strarray = filename.split("\\.");
    int suffixindex = strarray.length -1;
    system.out.println(strarray[suffixindex]);
  }
}

public class test {
  public static void main(string[] args) {

    string filepath = "e:\\test\\test.dxf";
    string filename = filepath.substring(filepath.lastindexof("\\")+1);
    system.out.println(filename);
    string extension=filename.substring(filename.lastindexof(".")+1,filename.length());
    system.out.println(extension);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网