Java Size Format formatFileSize(long length)

Here you can find the source of formatFileSize(long length)

Description

Formats the given file size into a nice string (123 bytes, 10.6 KB, 1.2 MB).

License

Open Source License

Parameter

Parameter Description
length The size

Declaration

public static String formatFileSize(long length) 

Method Source Code

//package com.java2s;
/**/*from   w w  w.j  a v  a2 s. c  om*/
 * Copyright 2011 The ARIES Consortium (http://www.ariesonline.org) and
 * www.integratedmodelling.org. 
    
   This file is part of Thinklab.
    
   Thinklab is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published
   by the Free Software Foundation, either version 3 of the License,
   or (at your option) any later version.
    
   Thinklab is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.
    
   You should have received a copy of the GNU General Public License
   along with Thinklab.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.text.DecimalFormat;

public class Main {
    public static final DecimalFormat KB_FORMAT = new DecimalFormat("#.# KB");
    public static final DecimalFormat MB_FORMAT = new DecimalFormat("#.# MB");

    /**
     * Formats the given file size into a nice string (123 bytes, 10.6 KB,
     * 1.2 MB).
     * @param length The size
     * @since jEdit 4.2pre1
     */
    public static String formatFileSize(long length) {
        if (length < 1024)
            return length + " bytes";
        else if (length < 1024 * 1024)
            return KB_FORMAT.format((double) length / 1024);
        else
            return MB_FORMAT.format((double) length / 1024 / 1024);
    }
}

Related

  1. formatFilesize(final long filesize, final Locale locale)
  2. formatFilesize(int s)
  3. formatFileSize(long fileS)
  4. formatFilesize(long filesize)
  5. formatFileSize(long fileSize, int decimalPos)
  6. formatFileSize(long size)
  7. formatFileSize(long size)
  8. formatFileSize(long size)
  9. formatFileSize(long size)