標籤: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基本操作,以及遞迴遍曆檔案夾