141

Possible Duplicate:
java get file size efficiently

I have a File called filename which is located in E://file.txt.

FileInputStream fileinputstream = new FileInputStream(filename);

What I want to do is to calculate the size of this file in bytes. How can I have this done?

Steven Bluen
  • 141
  • 2
  • 11
Illep
  • 16,375
  • 46
  • 171
  • 302

4 Answers4

303

You can use the length() method on File which returns the size in bytes.

Swapnil
  • 8,201
  • 4
  • 38
  • 57
  • 2
    This is a perfect answer, and I know I have done a bunch of weird things to get this in the past to get the size of a file. Wish I knew about this a long time ago! – RESTfulGeoffrey Jul 14 '18 at 07:08
54

You don't need FileInputStream to calculate file size, new File(path_to_file).length() is enough. Or, if you insist, use fileinputstream.getChannel().size().

Hui Zheng
  • 10,084
  • 2
  • 35
  • 40
8

You can do that simple with Files.size(new File(filename).toPath()).

akaIDIOT
  • 9,171
  • 3
  • 27
  • 30
7
public static void main(String[] args) {
        try {
            File file = new File("test.txt");
            System.out.println(file.length());
        } catch (Exception e) {
        }
    }
Avinash Nair
  • 1,984
  • 2
  • 13
  • 17