構(gòu)造方法
(推薦教程:java入門教程)
file f = new file("文件路徑")file f = new file("parent","child")創(chuàng)建一個(gè)文件:
//在工作空間目錄下創(chuàng)建a.txt的文件 file f = new file("a.txt"); f.createnewfile(); 在g:\\\\路徑下創(chuàng)建一個(gè)a.txt的文件.如果已經(jīng)有的話這不會(huì)重新創(chuàng)建 file f = new file("g:\\\\\\\\a.txt"); f.createnewfile(); 如果路徑寫成\\\\\\\\a.txt,會(huì)在盤符下創(chuàng)建新的文件 file f = new file("\\\\\\\\a.txt"); f.createnewfile();創(chuàng)建一個(gè)文件夾:
//在工作空間目錄下創(chuàng)建a.txt的文件夾 file f = new file("a"); f.mkdir(); 在g:\\\\路徑下創(chuàng)建一個(gè)a.txt的文件夾.如果已經(jīng)有的話這不會(huì)重新創(chuàng)建 file f = new file("g:\\\\\\\\a"); f.mkdir(); 如果路徑寫成\\\\\\\\a.txt,會(huì)在盤符下創(chuàng)建新的文件夾 file f = new file("\\\\\\\\a"); f.mkdir(); 在g盤下創(chuàng)建文件夾a,a 下創(chuàng)建一個(gè)b文件夾 file f = new file("g:\\\\\\\\a\\\\\\\\b"); f.mkdirs(); //注意mkdirs(),創(chuàng)建多個(gè)文件夾new file 的區(qū)別:
file f = new file("a");//此時(shí)f是文件夾file f = new file("parent","child"); //此時(shí)f是文件,parent文件夾下的文件注意:此時(shí)會(huì)在盤符根目錄下創(chuàng)建文件夾 或文件 dfile f = new file("", "d");f.createnewfile(); // f.mkdir()(視頻教程推薦:java視頻教程)
list()方法與listfiles()方法區(qū)別:
f.list(); 返回string[]數(shù)組.里面包含了f一級(jí)目錄下的文件和文件夾名. 注意: 如果f:\\\\\\\\a\\\\\\\\b.那么b不會(huì)包含在數(shù)組中 f.listfiles() 返回file[]數(shù)組.里面包含了f一級(jí)目錄下的文件和文件夾. 注意: 如果f:\\\\\\\\a\\\\\\\\b.那么b不會(huì)包含在數(shù)組中文件名過(guò)濾器 filenamefilter
在f1的文件夾中過(guò)濾出后綴名為 "txt"的文件
代碼實(shí)現(xiàn):
string[] s = f1.list(new filenamefilter() { / * dir 需要被過(guò)濾的文件夾 name 需要?jiǎng)e被過(guò)濾的文 件名 .此名是相對(duì)路徑 * 如果返回true 則證明是符合條件的文件.會(huì)將改文件返回到數(shù)組中 */ @override public boolean accept(file dir, string name) { file f = new file(dir, name); if (f.isdirectory()) { return false; } if (f.getname().endswith("txt")) { return true; } return false; } });文件過(guò)濾器 filefilter filenamefilter
在f1文件夾中過(guò)濾出文件長(zhǎng)度大于20m的文件.
代碼實(shí)現(xiàn):
file[] fs = f1.listfiles(new filefilter() { / * pathname 表示要被過(guò)濾的文件,注意:不是文件名 * 返ture 證明是符合條件的文件 */ @override public boolean accept(file pathname) { if (pathname.length() > 1024 * 1024 * 20) { return true; } return false; } });絕對(duì)路徑與相對(duì)路徑
絕對(duì)路徑 g:\\\\\\\\a.txt 相對(duì)路徑 a.txt. //相對(duì)于工作空間的路徑( g:\\\\andirodworkspace\\\\a.txt)