×

Java Get File Size

There are three ways to get the file size in Java.

  1. Using Java InputOutput
  2. Using NewInputOutput Library
    • Files.size() Method
    • FileChannel.size() Method
  3. Using Apache Commons InputOutput

Using Java InputOutput:

The Java IO package offers the classes that deal with file-related operations. The File class, which provides the length() function, is also provided by the Java IO package.This gives the supplied file's size in bytes. If the file represents a directory, it returns an undefined value. You can use the method whether you're running Java 7 or an earlier version.

Pathnames for files and directories are represented abstractly using the Java File class. It is a component of the java.io package.

The path to the file was parsed as a parameter and produced as a function Object() { [native code] } of the Files class in the program below. The class's following methods have been employed by us:

  • exists(): This method determines whether or not the directory or file specified by this abstract pathname already exists. If and only if the requested path exists, it returns true; otherwise, it returns false.
  • isFile(): Determines if the file represented by this abstract pathname is a typical file. A file is normal if it is not a directory and also meets additional system-specific requirements. A Java application will always produce a normal file, regardless of whether it is a directory or not. If and only if the file indicated by this abstract pathname exists and is a regular file, it returns true; otherwise, it returns false.
  • length(): The method length() returns the size of the file identified by this fictitious pathname. In the event that this pathname refers to a directory, the return value is undefined.

Java Program to Demonstrate get File Size

import java.io.File;  
public class FS1   
{  
//path of the file    
static final String PATH = "C:\\Users\\JHON\\Desktop\\ X.pdf";  
public static void main(String args[])   
{  
//constructing the File class's function Object() { [native code] } and supplying the file's path to it
File f = new File(PATH);  
//determines whether the supplied exists or is a regular file (not a directory)
if (!f.exists() || !f.isFile())   
return;  
//prints f size in bytes  
System.out.println(sizeInBytes(f));  
//prints f size in KiloBytes
System.out.println(sizeInKiloBytes(f));  
//prints f size in MegaBytes
System.out.println(sizeInMegaBytes(f));  
}  
//the method calculates the file size in megabytes  
private static String sizeInMegaBytes(File f)   
{  
return (double) f.length() / (1024 * 1024) + " megabytes";  
}  
//the method calculates the file size in kilobytes  
private static String sizeInKiloBytes(File f)   
{  
return (double) f.length() / 1024 + " kilobytes";  
}  
//the method calculates the file size in bytes  
private static String sizeInBytes(File f)   
{  
return f.length() + " bytes";  
}  
}  

Output:

Java get File Size

Using Java NewInputOutput Library

Another Java IO library is NIO. Compared to the traditional IO library, it offers an alternative method of working with I/O. It's a different IO API. The library's foundation for I/O operations is a buffer-oriented, channel-based strategy.

Files.size() method:

The class Files is available thanks to the Java NIO library. It is a part of the java.nio.file package. The class has static methods that can be used with files, directories, or other file types. Most of the time, the file operations are delegated by the class' methods to the corresponding file system provider.

The Files class includes a method called size() that returns the file size. The size() method has the following syntax:

Public static long size (Path path) throws IOexception

The method returns the file size in bytes and accepts the file path as an argument.

// java program to demonstrate getFileSize2
import java.nio.file.Files;  
import java.nio.file.Path;  
import java.io.IOException;  
import java.nio.file.Paths;  
public class FS2   
{  
public static void main(String args[])   
{  
//path of the file    
String FN = "C:\\Users\\jhon\\Desktop\\y.mp3";  
//method calling  
FS(fileName);  
}  
//function that calculates the size of the file  
private static void FS(String FN)   
{  
//Path: It is an interface for finding files in file systems, and it usually reflects a system-specific file path.
//Paths: It is a class that only contains static methods. it converts a path string or URI and then returns a Path. The specified URI is transformed into a Path object via the get() function.
Path p = Paths.get(FN);  
try   
{  
//calling the Files class's size() function, which returns the file's size in bytes, and putting the result in the bytes variable
long bytes = Files.size(p);  
//uses the provided format string and arguments to call the String class's format() function, which produces a formatted string.
System.out.println(String.format("%, d bytes", bytes));  
System.out.println(String.format("%, d kilobytes", bytes / 1024));  
}   
catch (IOException e)   
{  
e.printStackTrace();  
}  
}  
}  

Output:

Java get File Size

FileChannel.size() Method

Another class called FileChannel is available from the Java NIO library. The java.nio.channels package contains this abstract class. The class has methods for reading, writing, mapping, and working with files.

To determine the file size, it offers the size() method. It gives the current file size in bytes for this channel.

public abstract long size() throws IOException  




// java program to demonstrate getFilesize
import java.nio.channels.FileChannel;  
import java.nio.file.Path;  
import java.io.IOException;  
import java.nio.file.Paths;  
public class FS3   
{  
//path of the file        
static final String P = "E:\\photos\\z.jpg";  
public static void main(String args[])   
{  
//Path: It is an interface for finding files in file systems, and it usually reflects a system-specific file path.
//Paths: It is a class that only contains static methods. it converts a path string or URI and then returns a Path. The specified URI is transformed into a Path object via the get() function.
Path p = Paths.get(P);  
//creating a reference variable of the FileChannel class  
FileChannel fc;  
try   
{  
//An invocation of this function behaves precisely the same as the invocation of fc.open(file, opts, new). It opens or creates a file and returns a file channel to access it.
FileAttribute<?>[0]);  
fc = FileChannel.open(path);  
//the size() method returns the file size in bytes  
long fileSize = fc.size();  
//prints the file size  
System.out.println(fileSize + " bytes");  
//calling the Channel interface's close() function to close the path
fc.close();  
}   
catch (IOException e)   
{  
e.printStackTrace();  
}  
}  
}  

Output:

1382132 bytes

Using Apache Commons IO

A third-party package called Apache Commons offers common tools for manipulating files. The org.apache.commons.io package contains the classes in question.

Using FileUtils.size of () method:

To determine the file size in bytes, use the class's sizeOf() method.

Syntax:

public static long sizeOf(File file)  

A file or directory can be passed as a parameter to the procedure. Keep in mind that the parameter can't be empty. If the input parameter is a regular file, it returns the file's length (in bytes). Recursively calculating the directory's size (in bytes) is done if the parameter is a directory.

Example:

import java.io.File;  
import org.apache.commons.io.FileUtils;  
public class FS4   
{  
//path of the file    
static final String P = "D:\\CAM\\cam.3.5.exe";  
public static void main(String args[])   
{  
//creating the File class constructor and passing the file path into it  
File f = new File(P);  
//get the file size  
long fileSize = FileUtils.sizeOf(f);  
//prints the file size  
System.out.println("The file size is: " +fileSize + " bytes");  
}  
}  

Output:

File size is: 65042816 bytes

Related Topics

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.