您好,登錄后才能下訂單哦!
本篇文章為大家展示了java中怎么獲取文件名和擴展名,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
如:文件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); }}
上述內(nèi)容就是java中怎么獲取文件名和擴展名,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。