0

I am writing a comparator class that compares the file size of one file to another file in the same directory. I am having trouble finding the right documentation to get the file size of a file.

Right now I am looking at the documentation here for getObjectSize:

http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize(java.lang.Object)

Here is my code, however it does not seem to be working.

public class FileComparator implements Comparator {

    private static Instrumentation instrumentation;

    @Override
    public int compare(Object o1, Object o2) {

        throw new UnsupportedOperationException("Not supported yet.");

    }

    static long getObjectSize(Object objectToSize) {

        return instrumentation.getObjectSize(objectToSize);

    }

}

public class Comparison {

    public static void main(String[] args) {

        File file = new File("src/Dummy1.pdf");

        System.out.println(FileComparator.getObjectSize(file));

    }

}

I get a NullPointerException thrown.

Sameer Anand
  • 311
  • 1
  • 4
  • 11
  • 3
    When you get a NullPointerException, read the stack trace. It'll tell you what is null, and at which line the error occurred. (This goes for many if not all runtime exceptions). I think your specific problem is that `instrumentation` hasn't been initialized. – keyser Dec 08 '13 at 20:28
  • http://www.javamex.com/tutorials/memory/instrumentation.shtml – Sotirios Delimanolis Dec 08 '13 at 20:29
  • Also, that method has _nothing_ to do with file size. – SLaks Dec 08 '13 at 20:30
  • Use `file.length()`. _Returns the length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist._ – Alexis C. Dec 08 '13 at 20:30
  • http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object http://stackoverflow.com/questions/116574/java-get-file-size-efficiently – eis Dec 08 '13 at 20:31

2 Answers2

2

You need to use file.length().

What you are currently trying to get is how much space a file Object takes in the RAM, which is not what you want.

skiwi
  • 66,971
  • 31
  • 131
  • 216
1

I think you need to initialize the instrumentation to get rid of NullPointerException

Try this:

 public int compare(Object o1, Object o2) {
    instrumentation = o2;
    throw new UnsupportedOperationException("Not supported yet.");

 }

Also use file.length() as you want to know the space which your file object takes

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331