java 核心編程 ——檔案操作類File,javafile

來源:互聯網
上載者:User

java 核心編程 ——檔案操作類File,javafile

1.概述

  對於檔案系統的訪問是每個語言必須的,java提供了File類來完成對檔案或者目錄的建立,重新命名,刪除,檔案清單的操作以及判讀是否存在。

2.對於檔案/目錄的操作

  操作內容包括:

    1:建立對象。

    2:判斷是否是目錄/檔案。

    3:判斷目錄或者檔案是否存在。

    4:修改檔案名稱。

    5:建立檔案/建立一個目錄/建立所有目錄。

    6:查詢目錄下所有目錄和檔案8輸出檔案路徑

    7:刪除檔案/目錄

  註:已上操作非必須全部一次使用

3.相關代碼

public static void main(String[] args) {        try {            File file = new File("D:\\test");            //建立一個目錄對象            File txt = new File("D:\\test\\tex.txt");    //建立一個檔案對象            System.out.println("ok");            if(!file.isDirectory()){     //判斷是否為目錄                if(!file.exists()){      //判斷目錄是否存在                    file.mkdir();       //建立一個目錄                    file.mkdirs();      //建立所有目錄                    System.out.println("ok");                }            }            if(!txt.isFile()){             //判斷是否為檔案                if(!txt.exists()){          //判斷檔案是否存在                    File newName = new File("D:\\test\\tex2.txt");    //建立一個檔案對象                    txt.renameTo(newName);     //重新命名檔案                    txt.createNewFile(); //建立一個新檔案,必須處理io異常                    System.out.println("ok");                }            }                        File path = new File("D:\\data\\log_Tyj");                File[]  files = path.listFiles(); //查詢目錄下的檔案清單            for (int i = 0; i < files.length; i++) {                System.out.println(files[i].getAbsolutePath()); //輸出對象的路徑            }            file.delete(); //刪除目錄,將刪除目錄下所有目錄和檔案            txt.delete(); //刪除檔案        } catch (IOException e) {            e.printStackTrace();        }    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.