16 comments on “How to get file size in Java

  1. Very helpful. How would we do this if the file resided somewhere on the internet, such as a JS file and get the size of the file via the url/filepath?

    Reply
  2. Hi, your posts are clear thanks alot, I have a problem here I am using java. security.Signature, I have created a signature with DSA for string characters, I need to print the size of that signature however, it gives me 64 always , even the signature with 10 character , any advice will be approciated ..
    Here is my code:
          try {
                    //Remetente Gera Assinatura Digital para uma Mensagem
                      SignerUser  signer = new SignerUser ();
                      String message =(“GTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTT”);
                      long start = System.currentTimeMillis();                
                    byte[] sign = signMessage(message.getBytes(), signer.getPrivateKey());
                    long time = System.currentTimeMillis() – start;
                     String s = Base64.getEncoder().encodeToString(sign);
                   
                    //Guarda Chave Pública para ser Enviada ao Destinatário
                    PublicKey pubKey = signer.getPubKey();
                    System.out.println(“signature of the massage is:  “ + sign );
                    System.out.println(“signature running  “ +time +” ms” );
                    System.out.println(s.length());

    Reply
  3. Interesting. Files.size() throws IOException while File.length() doesn’t. They must have been implemented differently.

    Reply
  4. Then where i can make changes in this code to make it measure the entered text by user ?

    Reply
  5. Wil it loads the file to the memory? Does calling file.length() iterate through each byte of the file? I mean, will it take the same time to call file.length() & print the chars in the file?

    Reply
    1. It only returns the file attribute, size in bytes.

      Reply
    1. You must come from the future, yottabyte in a laptop?

      Reply
  6. Hey mkyong,

    I just wanted to tell you that I keep getting to your posts and I love them.
    Always deliver, simple clean and reproducable results. Keep the work up, even
    the simple tricks sometimes help.

    Thanks,
    @kjellski

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *