137

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
  • 142
  • 2
  • 11
Illep
  • 15,441
  • 42
  • 155
  • 275

4 Answers4

292

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

Swapnil
  • 8,001
  • 4
  • 36
  • 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
50

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
  • 9,694
  • 2
  • 32
  • 39
7

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

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