Here you can find the source of formatBytes(long bytes)
Parameter | Description |
---|---|
bytes | The number of bytes. |
public static String formatBytes(long bytes)
//package com.java2s; /*//from w w w . j a v a 2 s . com * Copyright 2006 The National Library of New Zealand * * 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 static final DecimalFormat MEGABYTE_FORMAT = new DecimalFormat("#,###.00MB"); public static final DecimalFormat KILOBYTE_FORMAT = new DecimalFormat("#,###.00KB"); /** * Format a number of bytes into Megabytes/Kilobytes depending on the quantity. * @param bytes The number of bytes. * @return A human readable string. */ public static String formatBytes(long bytes) { if (bytes > 1024 * 1024) { return MEGABYTE_FORMAT.format(((double) bytes) / (1024 * 1024)); } else if (bytes > 1024) { return KILOBYTE_FORMAT.format(((double) bytes) / (1024)); } else { return Long.toString(bytes) + "B"; } } }