Here you can find the source of formatSize(long size)
Parameter | Description |
---|---|
size | a parameter |
public static String formatSize(long size)
//package com.java2s; /*/*from w w w .ja v a2 s . c om*/ * Copyright 2012 James Moger * * 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 { public final static long KILOBYTE = 1024L; public final static long MEGABYTE = 1024L * 1024L; public final static long GIGABYTE = 1024L * 1024L * 1024L; /** * Formats a file size as a human-readable string. * @param size * @return human-readable file size */ public static String formatSize(long size) { if (size < 1024) { return size + " bytes"; } double sz = size; String units; double nsz; String format = "0"; if (size >= GIGABYTE) { nsz = sz / GIGABYTE; units = "GB"; format = "0.0"; } else if (size >= MEGABYTE) { nsz = sz / MEGABYTE; units = "MB"; format = "0.0"; } else { nsz = sz / KILOBYTE; units = "KB"; } return new DecimalFormat(format).format(nsz) + " " + units; } }