File對(duì)象是對(duì)文件操作最常用的類(lèi),平常工作總用的很多,貼出來(lái)了幾個(gè)我工作常用的幾個(gè)方法。簡(jiǎn)單總結(jié)了下
直接上代碼:
//構(gòu)建文件對(duì)象 File file=new File("E:/android_demo/a"); File fileTest=new File("E:/android_demo/a/test.mp3"); //獲取文件的父路徑 File f=file.getParentFile(); System.out.println("f=="+f);//E:\android_demo //判斷文件是否存在 boolean is=file.exists();//不存在,返回fasle System.out.println("is=="+is); //獲取文件的絕對(duì)路徑可以理解等同getPath String path1=file.getAbsolutePath(); System.out.println("path=="+path1);//E:\android_demo\a //獲取文件的路徑 String path2=file.getPath(); System.out.println("path2=="+path2);//E:\android_demo\a //獲取當(dāng)前文件名 String s=file.getName(); System.out.println("s==="+s); //創(chuàng)建一個(gè)文件夾,即:E:/android_demo/a file.mkdir(); //創(chuàng)建一個(gè)文件,即:E:/android_demo/a/test.mp3 fileTest.createNewFile(); //文件大小,文件存儲(chǔ)時(shí)占用的字節(jié)數(shù); long l=f.length(); System.out.println("l=="+l); //獲取文件路徑string String str=fileTest.toString(); System.out.println("str=="+str);// E:\android_demo\a\test.mp3 //給文件重新命名 File fileTest2=new File("E:/android_demo/a/test2.mp3"); boolean b2=fileTest.renameTo(fileTest2); System.out.println("b2=="+b2);// E:/android_demo/a/test2.mp3 //刪除文件 boolean b3=fileTest.delete(); //刪除文件夾,注意刪除的文件夾下面必須沒(méi)有文件才可以刪除,有的話要便利刪除所有文件,然后才刪除 boolean b4=file.delete();
以上這篇java之File對(duì)象對(duì)文件的操作常用的幾個(gè)方法(推薦)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
標(biāo)簽:平頂山 茂名 長(zhǎng)白山 仙桃 唐山 貴港 惠州 潛江
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《java之File對(duì)象對(duì)文件的操作常用的幾個(gè)方法(推薦)》,本文關(guān)鍵詞 java,之,File,對(duì)象,對(duì),文件,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。