很多朋友都想知道java如何獲取文件名后綴?下面就一起來了解一下吧~
1、獲取文件類型(后綴名):
方法一:split分割:如果用“.”作為分隔的話,必須是如下寫法,String.split("\."),這樣才能正確的分隔開,不能用String.split(".")
String?filename?=?"file.txt";//?文件名 ????String[]?strArray?=?filename.split("\\."); ????????int?suffixIndex?=?strArray.length?-1; ????????System.out.println(strArray[suffixIndex]);
方法二:
substring截取:substring(int beginIndex, int endIndex)返回從開始位置(beginIndex)到目標位置(endIndex)之間的字符串,但不包含目標位置(endIndex)的字符。
File?file=new?File("E:\\file.doc");? String?fileName=file.getName();???? String?fileTyle=fileName.substring(fileName.lastIndexOf("."),fileName.length());? System.out.println(fileTyle);
2、獲取文件名:
方法一:split分割
String?fileName="E:\\file.docx"; String?temp[]=fileName.split("\\\\"); String?fileNameNow=temp[temp.length-1]; System.out.println(fileNameNow);
方法二:substring截取
String?fileName="E:\\file.pdf"; String?fileNameNow?=?fileName.substring(fileName.lastIndexOf("\\")+1); System.out.println(fileNameNow);
3、獲取文件前綴名:
//獲取文件名? String?filename?=?"file.docx";???????? String?caselsh?=?filename.substring(0,filename.lastIndexOf(".")); System.out.println(caselsh);
以上就是小編今天的分享,希望能幫到大家。