File

關(guān)于文件和文件夾的操作,我們使用的都是一個類:File

常用的構(gòu)造器 說明
File(String pathname) 將指定的路徑名轉(zhuǎn)換成一個File對象
File(String parent,String child) 根據(jù)指定的父路徑和文件路徑創(chuàng)建對象

方法:

File類常用方法
boolean createNewFile() 當(dāng)指定文件(或文件夾)不存在時創(chuàng)建文件并返回true,否則返回false,路徑不存在則拋出異常
boolean mkdir() 當(dāng)指定文件(或文件夾)不存在時創(chuàng)建文件夾并返回true,否則返回false
boolean mkdirs() 創(chuàng)建指定文件夾,所在文件夾目錄不存在時,則順道一塊創(chuàng)建
boolean delete() 刪除文件  。要刪除一個目錄,需要先刪除這個目錄下的所有子文件和子目錄
boolean renameTo(File dest) 將當(dāng)前File對象所指向的路徑修改為指定File所指的路徑 (修改文件名稱)
boolean exists() 是否存在
boolean isFile() 是否為一個文件
boolean isDirectory() 是否是一個目錄
String getPath() 獲取文件路徑

獲取文件的信息

指定一個目錄,在目錄下創(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制作目錄瀏覽器

這個程序出了 File ,還需要使用到數(shù)學(xué)上的一個概念「遞歸」。在代碼中就是方法在內(nèi)部代碼中可以調(diào)用自身,但是需要有正常的技術(shù)方式,否則無法停止的話在可能會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);            }        }    }}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容