Languages
[Edit]
EN

Java - get file size

0 points
Created by:
Dirask Admin - Marwin
1430

In this article, we would like to show you how to get file size in Java.

Below we present 3 methods of getting the file size:

  • File.length()
  • Files.size()
  • FileChannel.size()

1. Using File.length() method.

import java.io.File;

public class Example {

    public static void main(String[] args) {
        File file = new File("C:\\projects\\file.txt");
        long fileSize = file.length();

        System.out.println("File size in bytes:     " + fileSize + " B");
        System.out.println("File size in kilobytes: " + fileSize / 1024 + " kB");
        System.out.println("File size in megabytes: " + fileSize / (1024 * 1024) + " mB");
    }
}

 Output: 

File size in bytes:     113804 B
File size in kilobytes: 111 kB
File size in megabytes: 0 mB
Java - get file size
File used in example - the file size is consistent with the program results.

2. Using Files.size() method.

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

public class Example {

    public static void main(String[] args) throws IOException {
        Path filePath = Paths.get("C:\\projects\\file.txt");
        long fileSize = Files.size(filePath);

        System.out.println("File size in bytes:     " + fileSize + " B");
        System.out.println("File size in kilobytes: " + fileSize / 1024 + " kB");
        System.out.println("File size in megabytes: " + fileSize / (1024 * 1024) + " mB");
    }
}

Output: 

File size in bytes:     113804 B
File size in kilobytes: 111 kB
File size in megabytes: 0 mB

3. Using FileChannel.size() method.

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Example {

    public static void main(String[] args) throws IOException {
        Path filePath = Paths.get("C:\\projects\\file.txt");
        FileChannel fileChannel = FileChannel.open(filePath);
        long fileSize = fileChannel.size();

        System.out.println("File size in bytes:     " + fileSize + " B");
        System.out.println("File size in kilobytes: " + fileSize / 1024 + " kB");
        System.out.println("File size in megabytes: " + fileSize / (1024 * 1024) + " mB");
    }
}

Output: 

File size in bytes:     113804 B
File size in kilobytes: 111 kB
File size in megabytes: 0 mB

Java - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join