Java java.nio.file.Files size() Method
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
- Type:
java.nio.file.Path - Description: Represents the file path object whose size is to be obtained
- Note:
- 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
- Meaning: Returns the size of the file, in bytes
- Feature:
- 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
- Trigger conditions:
- 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
- Trigger conditions: When a security manager exists and denies access to the file
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
-
Performance considerations:
size() operations are usually fast-
Symbolic links:
-
File locking:
-
Alternatives:
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 java.nio.file.Files