File class為了檔案、目錄提供了對應的java物件,我們可以用它來建立、摻除或變更檔案的屬性
我們可以用三種方式來創造一個file Object
- 路徑名稱
- 爸爸資料夾的名稱和小孩資料夾的名稱
- URI (uniform resource identifier)
例子
//假設我有一個檔案路徑是C:\\myDir\myFile.txt
File(String pathname)
//File myDir = new File("C:\\myDir")
//File myFile = new File("C:\\myDir\\myFile.txt")
File(File parent, String child)
//File myFile = new File("C:\\myDir","myFile.txt")
File(String parent, String child)
//File myDir = new File("C:\\myDir")
//File myFile = new File(myDir,"myFile.txt")
File(URI uri)
我在使用File建構元的時候
- 並沒有實際在檔案系統中建立檔案
- 沒有讀寫或修改檔案內容
- 檔案可以已經存在獲釋後建立都沒有影響
File類別範例
package com.iii.jerry;
import java.io.File;
public class iotest {
public static void main(String[] args) {
File dir = new File("C:\\javawork2");//建立目錄物件
String contents[]=dir.list();//取得目錄中的目錄與檔案陣列
if(!dir.isDirectory()){//如果他"不"是目錄就回傳true,並說不是目錄,其餘false
System.out.println("Not a directory");
}else if (contents.length==0){//contents.length==0代表沒有任何檔案或是目錄,秀出為空
System.out.println("目錄"+dir.getName()+"內無檔案");
}else{
for(int i = 0;i<contents.length; i++){//目錄和檔案名稱一個一個列出來
System.out.println(contents[i]);
}
}
}
}
路徑
The absolute path identifies the file uniquely on a file system. A canonical path is the simplest path that uniquely identifies the file on a file system.
We can use the getAbsolutePath() and getCanonicalPath() methods to get the absolute and canonical paths represented by a File object, respectively.
The code above generates the following result.
package com.iii.jerry;
import java.io.File;
import java.io.IOException;
public class path {
public static void main(String[] args) {
printFilePath("C:\\javawork2\\test.txt");
printFilePath(".." + File.separator + "notes.txt");//File.separator會依照不同的os做改變window是"/"
}
public static void printFilePath(String pathname) {
File f = new File(pathname);
System.out.println("File Name: " + f.getName());
System.out.println("File exists: " + f.exists());
System.out.println("Absolute Path: " + f.getAbsolutePath());
try {
System.out.println("Canonical Path: " + f.getCanonicalPath());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
輸出結果:
File Name: test.txt
File exists: true
Absolute Path: C:\javawork2\test.txt
Canonical Path: C:\javawork2\test.txt
File Name: notes.txt
File exists: false
Absolute Path: D:\JDBC\workspace\Basic\..\notes.txt
Canonical Path: D:\JDBC\workspace\notes.txt
File separator
Different operating systems use a different character to separate two parts in a pathname.
For example, Windows uses a backslash (\) as a name separator in a pathname
The File class defines a constant named separator Char, which is the system-dependent name separator character.
We can use the File.separator Char constant to get the name separator as a character.
The File.separator
constant gives we the name separator as a String.
Using the name separator in your program will make your Java code work on different platforms.