構(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)建文件夾 或文件 d File 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ù)組中
文件名過濾器 FilenameFilter
在f1的文件夾中過濾出后綴名為 "txt"的文件
代碼實(shí)現(xiàn):
String[] s = f1.list(new FilenameFilter() { /** * dir 需要被過濾的文件夾 name 需要?jiǎng)e被過濾的文 件名 .此名是相對(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; } });
文件過濾器 FileFilter FilenameFilter
在f1文件夾中過濾出文件長度大于20M的文件.
代碼實(shí)現(xiàn):
File[] fs = f1.listFiles(new FileFilter() { /** * pathname 表示要被過濾的文件,注意:不是文件名 * 返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:andirodWorkspacea.txt)