该程序旨在创建一个GUI组件,该组件显示总空间量,可用空间和总可用空间的百分比:
package com.java24hours;
import java.io.IOException;
import java.nio.file.*;
import javax.swing.*;
public class FreeSpacePanel extends JPanel {
JLabel spaceLabel = new JLabel("Disk space: ");
JLabel space = new JLabel();
public FreeSpacePanel() {
super();
add(spaceLabel);
add(space);
try {
setValue();
} catch (IOException ioe) {
space.setText("Error");
}
}
private final void setValue() throws IOException {
// get the current file storage pool
Path current = Paths.get("");
FileStore store = Files.getFileStore(current);
// find the free storage space
long totalSpace = store.getTotalSpace();
long freeSpace = store.getUsableSpace();
// get this as a percentage (with two digits)
double percent = (double)freeSpace / (double)totalSpace * 100;
percent = (int)(percent * 100) / (double)100;
// set the label's text
space.setText(freeSpace + " free out of " + totalSpace + " ("
+ percent + "%)");
}
}
您可以看到创建了一个名为“ store”的FileStore对象,然后在以下几行中直接调用FileStore方法getTotalSpace()
和getUseableSpace()
,而无需执行。但是,FileStore类将这些方法声明为抽象的,那怎么可能呢?
答案 0 :(得分:3)
Files.getFileStore
返回实现所需方法的FileStore
的一些非抽象子类的实例。
要查看它是什么类,请执行以下操作:
System.out.println(store.getClass());
在Linux系统上,我看到该对象是类sun.nio.fs.LinuxFileStore
的实例。