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.