File類
- 創建File物件
需要導包:import java.io.File;
常見File物件的構造方法
| 方法宣告 | 功能描述 |
|---|---|
| File(String pathname) | 通過指定的檔案型別創建物件 |
| File(String parent, String Child) | 根據指定的父路徑和字串型別的子路徑創建物件 |
| File(File parent, String Child) | 根據指定的File類父路徑和字串型別的子路徑創建物件 |
若只處理一個目錄或檔案并知道路徑使用第一個比較方便處理多個使用二或三,
例子:
import java.io.File;
public class Test{
public static void main(String[] args){
File f = new File("D:\\file\\a.text);
File f1 = new File("src\\Hell.java);
System.out.println(f);
System.out.println(f1);
}
}
File類常用方法
1,public boolean createNewFile() throws IOException 創建新檔案
2,public boolean mkdirs() 創建新的目錄,若父目錄不存在,會自動創建
3,public boolean renameTo(File dest) 重命名檔案
4,public boolean isFile() 判斷是否是檔案
5,public boolean isDirectory() 判斷目錄是否存在
6,public boolean exists() 判斷檔案或者目錄是否存在
7,public boolean canRead() 判斷檔案是否可讀
8,public boolean canWrite() 判斷檔案是否可寫
9,public boolean isFile() 判斷File物件是否為檔案不是目錄
10,public String getAbsolute() 獲取絕對路徑
11,public String getPath() 獲取相對路徑
12,public String getName() 獲取檔案或目錄名
13,public long length() 獲取檔案大小(應用例如:用于限制上傳檔案大小)
14,public long lastModified() 獲取檔案最后一次修改的時間(單位,毫秒)
位元組流
在jdk中提供了兩個抽象類InputStream和OutputStream,所有位元組輸入流繼承自InputStream,所有位元組輸出流繼承自OutputStream,
以程式作為參考InputStream是將資料傳入程式中,OutputStream是將資料從程式中輸出出來,
InputStream常用方法
| int read() | 從輸入流讀取一個8位的位元組轉化為整數并回傳這個整數 |
|---|---|
| void close() | 關閉此輸入流與關聯的所有資源 |
OutputStream常用方法
| void write(int b) | 向輸入流寫入一個位元組 |
|---|---|
| void flush() | 重繪此輸入流并強制寫出所有緩沖的輸出位元組 |
| void close() | 關閉此輸出流與關聯的所有資源 |
InputStream讀檔案
InputStream是I/O包中用來讀檔案的類
其中的FileInputStream是InputStream的子類,專門用來讀取檔案中的資料
OutputStream寫檔案
同樣OutputStream是I/O包中用來讀檔案的類
其中的FileOutputStream是OutputStream的子類,專門用來把資料寫入檔案,
由于在I/O流進行讀寫操作時會出現例外可能會導致資料丟失,我們應使用throws關鍵字將例外拋出,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/277768.html
標籤:其他
