length()函数是Java中File类的一部分。该函数返回此抽象路径名为length表示的文件的长度。该函数返回代表位数的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并设置文件的路径。