Java File Size Get getFileSizeLabel(long sizeInBytes)

Here you can find the source of getFileSizeLabel(long sizeInBytes)

Description

get File Size Label

License

Apache License

Declaration

public static String getFileSizeLabel(long sizeInBytes) 

Method Source Code

//package com.java2s;
/*/*ww  w .ja v a 2 s .  c  om*/
 *    Copyright 2016 Roche NimbleGen Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.text.DecimalFormat;

public class Main {
    private static final DecimalFormat DF = new DecimalFormat("###,###.##");
    private static final String GB = "GB";
    private static final String MB = "MB";
    private static final String KB = "KB";
    private static final String BYTES = "B";

    public static String getFileSizeLabel(long sizeInBytes) {
        double divisor;
        String units = "";
        if (sizeInBytes > Math.pow(10, 9)) {
            divisor = Math.pow(10, 9);
            units = GB;
        } else if (sizeInBytes > Math.pow(10, 6)) {
            divisor = Math.pow(10, 6);
            units = MB;
        } else if (sizeInBytes > Math.pow(10, 3)) {
            divisor = Math.pow(10, 3);
            units = KB;
        } else {
            divisor = 1.0;
            units = BYTES;
        }

        double relativeSize = (double) sizeInBytes / divisor;
        String fileSizeLabel = "";

        synchronized (DF) {
            fileSizeLabel = DF.format(relativeSize) + units;
        }

        return fileSizeLabel;
    }
}

Related

  1. getFilesize(String path)
  2. getFileSize2(String filename)
  3. getFileSizeAggregate(String[] files)
  4. getFileSizeFormat(double inputvalue)
  5. getFileSizeFormat(String total_size)
  6. getFileSizeRecursive(File file, boolean subFolders)
  7. getFileSizes(File f)
  8. getFileSizeString(File file, boolean si)
  9. getFilesizeString(long size)