Java.io.File.length() 方法
描述
java.io.File.length() 返回此抽象路径名定义的文件的长度。 如果此路径名定义了目录,则返回值未指定。
声明
以下是 java.io.File.length() 方法的声明 −
public long length()
参数
NA
返回值
该方法返回此抽象路径名表示的文件的长度(以字节为单位)。
异常
SecurityException − 如果安全管理器存在并且其 SecurityManager.checkRead(java.lang.String) 方法拒绝对文件的读取访问权限
示例
下面的例子展示了 java.io.File.length() 方法的使用。
package com.tutorialspoint;
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
File f = null;
String path;
long len;
boolean bool = false;
try {
// create new file
f = new File("c:/test.txt");
// true if the file path is a file, else false
bool = f.exists();
// if path exists
if(bool) {
// returns the length in bytes
len = f.length();
// path
path = f.getPath();
// print
System.out.print(path+" file length: "+len);
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
ABCDE
让我们编译并运行上面的程序,这将产生下面的结果 −
c:\test.txt file length: 5

