Java - File Input Output File System

Introduction

FileSystem class represents a file system in a Java program.

A FileSystem object is platform-dependent.

To obtain the default FileSystem object for a platform, use the getDefault() static method of the FileSystems class.

// Create the platform-specific default file system object
FileSystem fs = FileSystems.getDefault();

A file system consists of one or more file stores which provides storage for files.

The getFileStores() method from FileSystem class returns an Iterator for the FileStore objects.

getRootDirectories() method of FileSystem class returns an iterator of Path objects, which represent paths to all top-level directories.

isReadOnly() method from FileSystem object returns if it only allows read-only access to the file stores.

The following code uses a FileSystem object and shows the file system information.

Demo

import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) {
    // Create the platform-specific default file system object
    FileSystem fs = FileSystems.getDefault();
    System.out.println("Read-only file system: " + fs.isReadOnly());
    System.out.println("File name separator: " + fs.getSeparator());

    System.out.println("\nAvailable file-stores are");

    for (FileStore store : fs.getFileStores()) {
      printDetails(store);//from   w w  w .  j  a  v  a  2s. c om
    }

    System.out.println("\nAvailable root directories are");

    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();
    }
  }
}

Result