如何通過java獲取檔名和副檔名
阿新 • • 發佈:2020-01-21
這篇文章主要介紹瞭如何通過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); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。