在Java中使用示例文件 getFreeSpace() 方法
getFreeSpace()函数是Java中 File 类的一部分。此函数返回抽象路径名表示的分区的未分配大小,如果路径名不存在则返回 0L。此函数提示分区的未分配空间,但不保证确切的字节数是空闲的。如果外部应用程序写入指定文件可能会导致错误,则写入操作可能不会成功。
函数签名:
public long getFreeSpace()
句法:
long var = file.getFreeSpace();
参数:此方法不接受任何参数。
返回值:函数返回long数据类型,表示分区的未分配大小,以字节为单位
异常:如果该方法不允许创建文件,则此方法抛出SecurityException
下面的程序说明了 getFreeSpace()函数的使用:
示例 1:文件“F:\\program.txt”是 F: Directory 中的现有文件。
// Java program to demonstrate
// getFreeSpace() method of File Class
import java.io.*;
public class solution {
public static void main(String args[])
{
// Create an abstract pathname (File object)
File f = new File("F:\\program.txt");
// Display the free size of the partition
// using the getFreeSpace() function
System.out.println("Free Space: "
+ f.getFreeSpace());
}
}
输出:
Free Space: 174491860992
示例 2:文件“F:\\program1.txt”在 F: 目录中不存在文件。
// Java program to demonstrate
// getFreeSpace() method of File Class
import java.io.*;
public class solution {
public static void main(String args[])
{
// Create an abstract pathname (File object)
File f = new File("F:\\program1.txt");
// Display the free size of the partition
// using the getFreeSpace() function
System.out.println("Free Space: "
+ f.getFreeSpace());
}
}
输出:
Free Space: 0
注意:这些程序可能无法在在线 IDE 中运行。请使用离线 IDE 并设置文件路径。