Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java java.nio.file.Files size() Method

Java java.nio.file.Files size() Method

Java File Java java.nio.file.Files


java.nio.file.Files.size() is a very practical static method in the Java NIO (New I/O) package, used to obtain the size of a specified file (in bytes). This method belongs to the java.nio.file package and is part of the file operation API introduced in Java 7.

Method Definition

public

static

long

size

(

Path path

)

throws

IOException

Method parameters

Path path

- Must point to an actual existing file - Cannot be a directory (otherwise an exception will be thrown) - The path can be an absolute or relative path

Return Value

long type

- If the file is empty, returns 0 - For large files, the return value may exceed `Integer.MAX_VALUE`

Exception handling

size() The method may throw the following exceptions:

IOException

- File does not exist - No permission to read the file - An input/output error occurs - The path points to a directory rather than a file

SecurityException


Usage examples

Basic Usage

Example

import

java.nio.file.*

;

import

java.io.IOException

;

public

class

FileSizeExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        Path filePath

=

Paths.

get

(

"example.txt"

)

;

       

       

try

{

           

long

fileSize

=

Files.

size

(

filePath

)

;

           

System

.

out

.

println

(

"File size: "

fileSize

" bytes"

)

;

       

}

catch

(

IOException

e

)

{

           

System

.

err

.

println

(

"Error getting file size: "

e.

getMessage

(

)

)

;

       

}

   

}

}

: Thrown when a security manager exists and denies access to the file

Example

// For potentially very large files, consider using a more friendly display method

public

static

String

formatFileSize

(

long

size

)

{

   

if

(

size

<

1024

)

return

size

" B"

;

   

int

exp

=

(

int

)

(

Math

.

log

(

size

)

/

Math

.

log

(

1024

)

)

;

   

char

unit

=

"KMGTPE"

.

charAt

(

exp

1

)

;

   

return

String

.

format

(

"%.1f %sB"

, size

/

Math

.

pow

(

1024

, exp

)

, unit

)

;

}


Notes

  1. Performance considerations:

  2. For the local file system,size() operations are usually fast
  3. For network file systems, there may be latency
  4. - For the local file system, the `size()` operation is usually fast - For network file systems, there may be latency
    1. Symbolic links:

    2. If the path is a symbolic link, the returned size is the actual file size pointed to by the link
    3. - If the path is a symbolic link, the returned size is the actual file size pointed to by the link
      1. File locking:

      2. The method does not lock the file during execution, so the file size may change immediately after being obtained
      3. - The method does not lock the file during execution, so the file size may change immediately after being obtained
        1. Alternatives:

        2. For older Java versions, you can use java.io.File.length()
        3. - For older Java versions, you can use `java.io.File.length()`

          Practical Application Scenarios

          Check before file upload:

          Example

          // Check whether the file exceeds the allowed size

          if

          (

          Files.

          size

          (

          filePath

          )

          MAX_UPLOAD_SIZE

          )

          {

             

          throw

          new

          FileTooLargeException

          (

          )

          ;

          }

          Disk space management:

          Example

          // Calculate the total size of all files in a directory

          long

          totalSize

          =

          Files.

          walk

          (

          dirPath

          )

                              .

          filter

          (

          Files

          ::

          isRegularFile

          )

                              .

          mapToLong

          (

          Files

          ::

          size

          )

                              .

          sum

          (

          )

          ;

          Progress display:

          Example

          // Display file copy progress

          long

          totalBytes

          =

          Files.

          size

          (

          sourcePath

          )

          ;

          long

          copiedBytes

          =

          0

          ;

          // ...Update and display the progress percentage in the copy loop...


          Frequently Asked Questions

          Q1: Can the size() method be used for directories?

          No. If the path points to a directory, it will throw IOException. To get the directory size, you need to use Files.walk() to traverse the directory contents and accumulate the file sizes.

          Q2: Will this method block?

          For the local file system, it usually does not block noticeably, but for network file systems there may be latency.

          Q3: Why is the return value long instead of int?

          Because some files may exceed 2GB (Integer.MAX_VALUE), using long can support extremely large files.

          Q4: What is the difference between this method and File.length()?

          Files.size() is part of the NIO.2 API and supports more modern file system features (such as symbolic links), while File.length() is a method of traditional I/O.


          Summary

          java.nio.file.Files.size() The method provides a simple and effective way to obtain file size and is a commonly used utility method in file operations. Understanding its usage and potential exceptions is very important for writing robust file processing code.

          Java File Java java.nio.file.Files