Java-io-file-length

提供:Dev Guides
移動先:案内検索

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.finddevguides;

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