📜  Java中的 FileStore getUsableSpace() 方法及示例

📅  最后修改于: 2022-05-13 01:55:51.448000             🧑  作者: Mango

Java中的 FileStore getUsableSpace() 方法及示例

FileStore类的getUsableSpace()方法用于返回文件存储中此Java虚拟机可用的字节数。此方法对于检查可用空间很有用。此方法将可用的可用空间作为 long 值返回。

句法:

public abstract long getUsableSpace()
                     throws IOException

参数:此方法不接受任何内容。

返回值:此方法将可用的可用空间作为长值返回。

异常:如果发生 I/O 错误,此方法将抛出IOException

下面的程序说明了 getUsableSpace() 方法:
方案一:

// Java program to demonstrate
// FileStore.getUsableSpace() method
  
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // create the object of Path
        Path path
            = Paths.get(
                "E:\\Tutorials\\file.txt");
  
        // get FileStore object
        try {
  
            FileStore fs
                = Files.getFileStore(path);
  
            // print FileStore name and Total usable space
            System.out.println("FileStore Name: "
                               + fs.name());
            long bytes = fs.getUsableSpace();
            long sizeInGB = bytes / (1024 * 1024);
            System.out.println("Usable Space: "
                               + sizeInGB + " MB");
        }
        catch (IOException e) {
  
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

输出:

方案二:

// Java program to demonstrate
// FileStore.getUsableSpace() method
  
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // create the object of Path
        Path path
            = Paths.get(
                "C:\\Movies\\001.txt");
  
        // get FileStore object
        try {
  
            FileStore fs
                = Files.getFileStore(path);
  
            // print FileStore name and Total usable space
            System.out.println("FileStore Name: "
                               + fs.name());
            long bytes = fs.getUsableSpace();
            long sizeInGB = bytes / (1024);
            System.out.println("Usable Space: "
                               + sizeInGB + " KB");
        }
        catch (IOException e) {
  
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

输出:

参考资料:https: Java/nio/file/FileStore.html#getUsableSpace()