Java的檔案流操作
檔案系統
FileSystem類的物件表示Java程式中的檔案系統。
FileSystem物件用於執行兩個任務:
Java程式和檔案系統之間的介面。
一個工廠用於建立許多型別的檔案系統相關物件和服務。
FileSystem物件與平臺相關。
建立檔案系統
要獲取預設的FileSystem物件,我們需要使用FileSystems類的getDefault()靜態方法,如下所示:
FileSystem fs = FileSystems.getDefault();
FileSystem由一個或多個FileStore組成。FileSystem的getFileStores()方法返回FileStore物件的Iterator。
FileSystem的getRootDirectories()方法返回Path物件的迭代器,它表示到所有頂級目錄的路徑。
FileSystem的isReadOnly()方法告訴我們是否獲得對檔案儲存的只讀訪問許可權。
例子
以下程式碼顯示如何使用FileSystem物件。
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
FileSystem fs = FileSystems.getDefault();
System.out.println("Read-only file system: " + fs.isReadOnly());
System.out.println("File name separator: " + fs.getSeparator());
for (FileStore store : fs.getFileStores()) {
printDetails(store);
}
for (Path root : fs.getRootDirectories()) {
System.out.println(root);
}
}
public static void printDetails(FileStore store) {
try {
String desc = store.toString();
String type = store.type();
long totalSpace = store.getTotalSpace();
long unallocatedSpace = store.getUnallocatedSpace();
long availableSpace = store.getUsableSpace();
System.out.println(desc + ", Total: " + totalSpace + ", Unallocated: "
+ unallocatedSpace + ", Available: " + availableSpace);
} catch (IOException e) {
e.printStackTrace();
}
}
}
為了讓學習變得輕鬆、高效,今天給大家免費分享一套Java教學資源。幫助大家在成為Java架構師的道路上披荊斬棘。需要資料的歡迎加入學習交流群:9285,05736
