java File基本操作,以及遞迴遍曆檔案夾

來源:互聯網
上載者:User

標籤:dom   避免   檔案操作   環境   字串   重要   遍曆   oid   directory   

java 的檔案操作,相對來說是比較重要的,無論是編寫CS還是BS程式,都避免不了要與檔案打交道,例如讀寫設定檔等。雖然現在很多架構都直接幫你做好了這一步!

java.io.File 底層是調用與c語言接的介面,所以我們暫時不需要知道底層是怎麼實現的,再說了,也看不見,最多就是看見一個介面而已。我們只需要知道java.io.File提供給我們對檔案的一些操作就行了。

1.檔案的建立

  :java的檔案建立可以直接通過new一個對象來實現。

  File file = new File(String pathName)

  File file = new File(String parent, String child)

  主要的就是這兩種建立檔案方式,第一種pathName是一個抽象路徑名。比如file = new File("E:/game/WM3.log"); 建立一個檔案叫做E:/game/WM3.log

  第二種就是抽象路徑名加上路徑名

  檔案操作的基本方法:

  boolean exists()  檔案是否已存在

  boolean createNewFile()  若且唯若指定抽象路徑名不存在時建立一個新的空檔案

  boolean delete()  刪除指定抽象路徑名的檔案

  File getAbsoluteFile()  返回抽象路徑名抽象路徑名形式

  String getAbsolutePath()  返回抽象路徑名的字串形式

  String getName()  返回抽象路徑名表示的檔案或路徑

  long length()  返回抽象路徑名的檔案長度

  String[] list()  返回抽象路徑名的檔案或目錄的字串數組

  File[] listFiles()  返回一個抽象路徑名數組,這些路徑名表示此抽象路徑名表示的目錄中的檔案

  File[] listFiles(FileFilter filter)  返回Filter過濾的抽象路徑名數組

  boolean mkdir()  建立一個路徑名為目錄

  boolean mkdirs()  建立多層的目錄,包括不存在的目錄的父目錄

  這些方法都是相對常用的,其他還有一些特殊環境使用的方法,當有需要是可以查API

2.遍曆抽象路徑路徑下的檔案以及所有子目錄

有兩種方法實現,但是我只實現用遞迴的方法

  import java.io.File;
  import java.io.FileNotFoundException;
  import java.io.IOException;
  import java.io.RandomAccessFile;
  import java.util.ArrayList;
  import java.util.List;

  /**
  * 主要複習檔案建立以及檔案價
  * @author heack
  *
  */
  public class DirAndFile {

  File or;
  File[] files;

  List<String> pathName = new ArrayList<String>();

  // 用於遍曆檔案價
  public void iteratorPath(String dir) {
    or = new File(dir);
    files = or.listFiles();
    if (files != null) {
      for (File file : files) {
        if (file.isFile()) {
          pathName.add(file.getName());
        }else if (file.isDirectory()) {
          iteratorPath(file.getAbsolutePath());
        }
      }
    }
  }

  public static void main(String[] args) {
    DirAndFile and = new DirAndFile();
    and.iteratorPath("E:/");
      for (String list : and.pathName) {
       System.out.println(list);
     }
  }
}

此隨筆為以後複習使用,也供新入java的同志解惑

java File基本操作,以及遞迴遍曆檔案夾

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.