search
HomeJavajavaTutorialJava program to get the size of a given file in bytes, kilobytes and megabytes

Java program to get the size of a given file in bytes, kilobytes and megabytes

File size is the amount of storage space that a specific file takes up on a specific storage device, such as a hard drive. The size of a file is measured in bytes. In this section, we will discuss how to implement a java program to get the size of a given file in bytes, kilobytes and megabytes.

Bytes are the smallest unit of digital information. One byte equals eight bits.

  • 1 Kilobyte (KB) = 1,024 bytes

  • 1 Megabyte (MB) = 1,024 KB

  • Gigabyte (GB) = 1,024 MB and

  • 1 terabyte (TB) = 1,024 GB.

The size of the file usually depends on the type of file and the amount of data it contains. Taking a text document as an example, the file size may be only a few kilobytes, while a high-resolution image or video file may be several gigabytes in size.

A file is a collection of information, which may contain text information, images, audio, video, program code and other data. Any software application can access them to perform operations such as reading, writing, updating, deleting, etc.

grammar

Create file object

File file = new File("file_path");

Create BufferedStramInout class object

BufferedInputStream input = new BufferedInputStream(new FileInputStream("filename"));

length() - This method returns the size of the file in bytes.

File file = new File("/example.txt");
long fileSize = file.length();

exists() - This method checks if the file exists and returns a boolean value.

File file = new File("/example.txt");
if (file.exists()) {
  System.out.println("File exists.");
}

read() - This method is used to read bytes from the input stream.

FileInputStream input = new FileInputStream(filePath)
byte[] buffer = new byte[10];
int bytesRead = input.read(buffer); 

size() - This method returns the size of the file in bytes.

Path path = Paths.get("/path/to/file");
long fileSize = Files.size(path);

Now, we will implement different java methods to find the size of a given file in bytes, kilobytes and megabytes.

Method 1: Use java.io. combo

In this particular method, we will use the File class of the java.io package and use different built-in functions and get the size of the file.

algorithm

  • Use the File class to create file objects.

  • Use the exists() method to check whether the file exists. If the file exists, use the length() method to find the size of the file.

  • Print size in bytes, kilobytes, megabytes.

  • If the file does not exist, print the file not found.

Example

In this example, we have created a file object using the File class, we will use the exists() function to check whether the file exists and calculate the length of the file if it exists Use the length() function to get the length of the file and store it in the "sizebytes" variable. We will use "sizebytes" to print the size of the file in bytes. For kilobytes, the size is "sizebytes" divided by 1024; for kilobytes, the size is "sizebytes" divided by 1024*1024.

import java.io.File;
public class Main{
   public static void main(String[] args) {
      File f = new File("C:/example.txt");
      if (f.exists()) {
         long sizebytes = f.length();
         System.out.println("File size in bytes is equal to : " + sizebytes);
         System.out.println("File size in kilobytes is equal to : " + (sizebytes/ 1024));
         System.out.println("File size in megabytes is equal to : " + (sizebytes / (1024 * 1024)));
      } else {
         System.out.println("File not found.");
      }
   }
}

Output

File size in bytes is equal to : 1048576 
File size in kilobytes is equal to : 1024
File size in megabytes is equal to : 1	

Method 2: Using the java.nio package

In this particular approach, we will use the Path class of the java.nio package and use different built-in functions and get the size of the file.

algorithm

  • Use the get() method of the Path class to create a path object.

  • Use the size() method to find the size and print the size in bytes, kilobytes, megabytes

  • If an exception occurs, print it

Example

In this example, we have created a file object using the Path class and we will use the size() function to get the size of the file and store it in 'sizebytes' variable. We will use 'sizebytes' to print the size of the file in bytes. For kilobytes, the size is "sizebytes" divided by 1024; for kilobytes, the size is "sizebytes" divided by 1024*1024.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
   public static void main(String[] args) {
      Path p = Paths.get("C:/example.txt");
      try {
         long sizebytes = Files.size(p);
         System.out.println("File size in bytes is equal to : " + sizebytes);
         System.out.println("File size in kilobytes is equal to : " + (sizebytes/ 1024));
         System.out.println("File size in megabytes is equal to : " + (sizebytes / (1024 * 1024)));
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
   }
}

Output

File size in bytes is equal to : 1048576 
File size in kilobytes is equal to : 1024
File size in megabytes is equal to : 1

So, in this article, we have discussed the different ways to get the size of a given file in Bytes, Kilobytes and Megabytes in Java.

The above is the detailed content of Java program to get the size of a given file in bytes, kilobytes and megabytes. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function