Java中的文件长度()方法与示例
length()函数是Java中 File 类的一部分。此函数返回由此抽象路径名表示的文件的长度是长度。该函数返回表示位数的 long 值,如果文件不存在或发生异常,则返回 0L。
函数签名:
public long length()
句法:
long var = file.length();
参数:此方法不接受任何参数。
返回类型该函数返回long 数据类型,表示文件的长度,以位为单位。
异常:如果拒绝对文件的写访问,此方法将引发安全异常
下面的程序说明了 length()函数的使用:
示例 1:文件“F:\\program.txt”是 F: 目录中的现有文件。
// Java program to demonstrate
// length() method of File Class
import java.io.*;
public class solution {
public static void main(String args[])
{
// Get the file
File f = new File("F:\\program.txt");
// Get the length of the file
System.out.println("length: "
+ f.length());
}
}
输出:
length: 100000
示例 2:文件“F:\\program1.txt”为空
// Java program to demonstrate
// length() method of File Class
import java.io.*;
public class solution {
public static void main(String args[])
{
// Get the file
File f = new File("F:\\program.txt");
// Get the length of the file
System.out.println("length: "
+ f.length());
}
}
输出:
length: 0
注意:这些程序可能无法在在线 IDE 中运行。请使用离线 IDE 并设置文件路径。