Java - File length() 方法



描述

Java File length() 方法返回由该抽象路径名定义的文件的长度。如果此路径名定义的是目录,则返回值未指定。

声明

以下是java.io.File.length() 方法的声明:

public long length()

参数

返回值

该方法返回由该抽象路径名表示的文件的长度(以字节为单位)。

异常

SecurityException - 如果存在安全管理器并且其SecurityManager.checkRead(java.lang.String) 方法拒绝读取文件的访问权限

示例 1

以下示例演示了 Java File length() 方法的使用。我们创建了两个 File 引用。然后,我们使用当前目录中不存在的 test.txt 创建一个 File 对象。然后,我们使用 createNewFile() 方法创建该文件。现在,使用 getAbsoluteFile() 方法获取文件,并使用 length() 方法获取文件长度并打印它。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      File f1 = null;
      
      try {
         // create new files
         f = new File("test.txt");
         
         // create new file in the system
         f.createNewFile();
         
         // create new file object from the absolute path
         f1 = f.getAbsoluteFile();
         
         // prints the file length
         System.out.print("File length: "+ f1.length());
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

File length: 0

示例 2

以下示例演示了 Java File length() 方法的使用。我们创建了一个 File 引用。然后,我们使用 F:/test1.txt 创建一个 File 对象,该文件存在于提供的目录中,但处于隐藏状态。现在,使用 getAbsoluteFile() 方法获取文件,并使用 length() 方法打印文件长度。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      
      try {
         // create new files
         f = new File("F:/test1.txt");         
    
         // get the file
         File f1 = f.getAbsoluteFile();
         
         // prints the file length
         System.out.println("File length: "+f1.length());
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果。我们假设 test.txt 包含以下内容:

This is a sample file.

输出将如下所示:

File length: 22

示例 3

以下示例演示了 Java File length() 方法的使用。我们创建了一个 File 引用。然后,我们使用 F:/test 目录创建一个 File 对象,该目录存在于提供的路径中,并且未隐藏。现在,使用 getAbsoluteFile() 方法获取目录,并使用 length() 方法获取其长度。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;     
      try {
         
         // create new files
         f = new File("F:/test");         
    
         // get the file
         File f1 = f.getAbsoluteFile();
         
         // prints the directory length
         System.out.println("Directory length: "+f1.length());
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Directory length: 4096
java_file_class.htm
广告
© . All rights reserved.