Dave's Brain

Browse - Programming Tips - In Java, how can I get a file's size (in bytes) ?

Date: 2016jan7
Language: Java
Level: beginner

Q.  In Java, how can I get a file's size (in bytes) ?

A.

long getSize(final String filename, final long defaultSize) { if (filename == null) return defaultSize; File file = new File(filename); if (!file.exists()) return defaultSize; return file.length(); }
void exampleUse() { long size = getSize("/etc/passwd", -1); if (size < 0) { // doesn't exist or I can't access it } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.