Java tutorial
//package com.java2s; /* This file is part of Subsonic. Subsonic 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. Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2009 (C) Sindre Mehus */ import java.text.DecimalFormat; import java.text.NumberFormat; public class Main { private static final DecimalFormat GIGA_BYTE_FORMAT = new DecimalFormat("0.00 GB"); private static final DecimalFormat MEGA_BYTE_FORMAT = new DecimalFormat("0.00 MB"); private static final DecimalFormat KILO_BYTE_FORMAT = new DecimalFormat("0 KB"); /** * Converts a byte-count to a formatted string suitable for display to the user. * For instance: * <ul> * <li><code>format(918)</code> returns <em>"918 B"</em>.</li> * <li><code>format(98765)</code> returns <em>"96 KB"</em>.</li> * <li><code>format(1238476)</code> returns <em>"1.2 MB"</em>.</li> * </ul> * This method assumes that 1 KB is 1024 bytes. * To get a localized string, please use formatLocalizedBytes instead. * * @param byteCount The number of bytes. * @return The formatted string. */ public static synchronized String formatBytes(long byteCount) { // More than 1 GB? if (byteCount >= 1024 * 1024 * 1024) { NumberFormat gigaByteFormat = GIGA_BYTE_FORMAT; return gigaByteFormat.format((double) byteCount / (1024 * 1024 * 1024)); } // More than 1 MB? if (byteCount >= 1024 * 1024) { NumberFormat megaByteFormat = MEGA_BYTE_FORMAT; return megaByteFormat.format((double) byteCount / (1024 * 1024)); } // More than 1 KB? if (byteCount >= 1024) { NumberFormat kiloByteFormat = KILO_BYTE_FORMAT; return kiloByteFormat.format((double) byteCount / 1024); } return byteCount + " B"; } }