關(guān)于文件和文件夾的操作堂湖,我們使用的都是一個(gè)類:File
常用的構(gòu)造器 | 說明 |
---|---|
File(String pathname) | 將指定的路徑名轉(zhuǎn)換成一個(gè)File對象 |
File(String parent,String child) | 根據(jù)指定的父路徑和文件路徑創(chuàng)建對象 |
方法:
File類常用方法 | |
---|---|
boolean createNewFile() | 當(dāng)指定文件(或文件夾)不存在時(shí)創(chuàng)建文件并返回true宇姚,否則返回false线定,路徑不存在則拋出異常 |
boolean mkdir() | 當(dāng)指定文件(或文件夾)不存在時(shí)創(chuàng)建文件夾并返回true,否則返回false |
boolean mkdirs() | 創(chuàng)建指定文件夾纪铺,所在文件夾目錄不存在時(shí)合瓢,則順道一塊創(chuàng)建 |
boolean delete() | 刪除文件 伸眶。要?jiǎng)h除一個(gè)目錄铣鹏,需要先刪除這個(gè)目錄下的所有子文件和子目錄 |
boolean renameTo(File dest) | 將當(dāng)前File對象所指向的路徑修改為指定File所指的路徑 (修改文件名稱) |
boolean exists() | 是否存在 |
boolean isFile() | 是否為一個(gè)文件 |
boolean isDirectory() | 是否是一個(gè)目錄 |
String getPath() | 獲取文件路徑 |
獲取文件的信息
指定一個(gè)目錄敷扫,在目錄下創(chuàng)建文件
public void createNewFile(String pathname) {
File file = new File("d:/",pathname);
if( !file.exists() ) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
創(chuàng)建方法:printFileInfo , 輸出文件相關(guān)的信息
public void printFileInfo(String pathname) {
File file = new File(pathname);
System.out.println("文件名:"+ file.getName());
System.out.println("文件路徑:"+ file.getPath());
System.out.println("文件的父路徑:"+ file.getParentFile());
System.out.println("文件是否存在:"+ file.exists());
System.out.println("是否為文件:"+ file.isFile());
System.out.println("是否為文件夾:"+ file.isDirectory());
}
使用File制作目錄瀏覽器
這個(gè)程序出了 File 诚卸,還需要使用到數(shù)學(xué)上的一個(gè)概念「遞歸」葵第。在代碼中就是方法在內(nèi)部代碼中可以調(diào)用自身,但是需要有正常的技術(shù)方式合溺,否則無法停止的話在可能會(huì)OOM的卒密。
方法名 | 說明 |
---|---|
String[] list() | 返回文件夾下面的文件名列表 |
File[] listFiles() | 返回文件夾下面的文件對象列表 |
public class FileExplorer { public static void main(String[] args) { File f = new File("D:\\epub"); printTree(f, 0); } public static void printTree(File f, int level) { for (int j = 0; j < level; j++) { System.out.print("\t"); } System.out.println(f.getAbsolutePath()); if (f.isDirectory()) { level++; File strs[] = f.listFiles(); for (int i = 0; i < strs.length; i++) { File f0 = strs[i]; printTree(f0, level + 1); } } }}