1. 程式人生 > 其它 >IO流(File類)

IO流(File類)

IO流(File類)

一,前言

​ 開始學習IO流,瞭解IO流的概念,掌握File類。。

二, IO流的概念

Java 的 IO 流主要包括輸入、輸出兩種 IO 流。

  • 輸入:讀取資料到記憶體中。
  • 輸出:將記憶體資料輸出外部中。

每種輸入、輸出流有可分為位元組流和字元流兩大類:

  • 位元組流以位元組為單位來處理輸入、輸出操作。
  • 字元流以字元為單位來處理輸入、輸出操作。

三,File類的概念

​ Java檔案類以抽象的方式代表檔名和目錄路徑名。該類主要用於檔案和目錄的建立、檔案的查詢和檔案的刪除等。

​ File 能新建、刪除、重新命名檔案和目錄,但 File 不能訪問檔案內容本身。如果需要訪問檔案內容本身,則需要使用輸入/輸出流。

四,File類的構造方法

//通過將給定路徑名字串轉換成抽象路徑名來建立一個新 File 例項。
File(String pathname) 

//根據 parent 路徑名字串和 child 路徑名字串建立一個新 File 例項。
File(String parent, String child)    

//通過將給定的 file: URI 轉換成一個抽象路徑名來建立一個新的 File 例項。
File(URI uri) 

五,File類的常用方法

//建立方法
boolean	createNewFile():
	建立檔案(當檔案不存在時)
boolean	mkdir():
	建立一級目錄
boolean	mkdirs():
	建立多級目錄

//刪除方法
boolean	delete():
	刪除檔案或目錄。

//測試方法
boolean	exists():
	測試檔案或目錄是否存在。
boolean	isDirectory():
	測試檔案是否為目錄。
boolean	isFile():
	測試檔案是否為普通檔案。

//查詢方法
String	getAbsolutePath():
	返回絕對路徑名字串。
String	getParent():
	返回上級絕對路徑。

//轉換方法
String[]	list():
	返回一個字串陣列,命名由此抽象路徑名錶示的目錄中的檔案和目錄。
File[]	listFiles():
	返回一個抽象路徑名陣列,表示由該抽象路徑名錶示的目錄中的檔案。

//其他方法
String	getName():
	返回由此抽象路徑名錶示的檔案或目錄的名稱。
long	length():
	返回由此抽象路徑名錶示的檔案的長度。

六,遞迴方法

​ 使用遞迴方法制一個多級資料夾到一個指定的目錄下:

public class Test02 {
	
	/*
	 * 複製一個多級資料夾到一個指定的目錄下
	 */
	
	public static void fz(String pathname,String path) throws IOException {	
		//定位檔案
		File file = new File(pathname);
		//如果不存在
		if (file.exists() == false) {
			throw new IOException("原始檔不存在");
				}
		//展示當下資料夾各檔名
		String str[] = file.list();
		//迴圈輸出
		for (String string : str) {
			//定位當下新檔案	
			File f = new File(pathname+"/"+string);
			//如果是資料夾
			if (f.isDirectory()) {	
				//建立複製處資料夾
				File newf = new File(path + "/" + string);
				newf.mkdir();
				//遞迴資料夾下的檔案,重複操作
				fz(pathname+"/"+string, path + "/" + string);
            //如果是檔案    
			}else {	
				//建立複製處檔案
				File newf = new File(path + "/" + string);
				newf.createNewFile();		
			
			}	
			
		}		
	}