Here you can find the source of formatBytes(long bytes)
Parameter | Description |
---|---|
bytes | Bytes. |
private static String formatBytes(long bytes)
//package com.java2s; /* Copyright (c) 2010 Daniel Doubrovkine, All Rights Reserved * // ww w .j a v a 2 s . c o m * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ public class Main { /** * Format bytes. * @param bytes * Bytes. * @return * Rounded string representation of the byte size. */ private static String formatBytes(long bytes) { if (bytes == 1) { // bytes return String.format("%d byte", bytes); } else if (bytes < 1024) { // bytes return String.format("%d bytes", bytes); } else if (bytes < 1048576 && bytes % 1024 == 0) { // Kb return String.format("%.0f KB", (double) bytes / 1024); } else if (bytes < 1048576) { // Kb return String.format("%.1f KB", (double) bytes / 1024); } else if (bytes % 1048576 == 0 && bytes < 1073741824) { // Mb return String.format("%.0f MB", (double) bytes / 1048576); } else if (bytes < 1073741824) { // Mb return String.format("%.1f MB", (double) bytes / 1048576); } else if (bytes % 1073741824 == 0 && bytes < 1099511627776L) { // GB return String.format("%.0f GB", (double) bytes / 1073741824); } else if (bytes < 1099511627776L) { return String.format("%.1f GB", (double) bytes / 1073741824); } else if (bytes % 1099511627776L == 0 && bytes < 1125899906842624L) { // TB return String .format("%.0f TB", (double) bytes / 1099511627776L); } else if (bytes < 1125899906842624L) { return String .format("%.1f TB", (double) bytes / 1099511627776L); } else { return String.format("%d bytes", bytes); } } }