📄 byteformatter.java
字号:
/*
* Copyright 2005-2007 JavaAtWork All rights reserved.
* Use is subject to license terms.
*/
package com.javaatwork.mydownloader.utils;
import java.text.DecimalFormat;
/**
* Class for formatting bytes to a String representation (b, Kb, Mb).
*
* @author Johannes Postma
*/
public class ByteFormatter {
private static DecimalFormat formatter = new DecimalFormat("#.00");
/**
* Formats bytes in a String representation in b, Kb, Mb or Gb.
* When the format is MB or Gb the format has two decimals.
*
* @param bytes The bytes.
* @return The String representation.
*/
public static String format(long bytes) {
// bytes
if (bytes < 1024) {
return Long.toString(bytes) + " b";
}
// kilo bytes
else if (bytes < (1024 * 1024)) {
double bytesSent = bytes / 1024.0;
return Math.round(bytesSent) + " Kb";
}
// mega bytes
else if (bytes < (1024 * 1024 * 1024)) {
double bytesSent = bytes / (1024.0 * 1024.0);
return formatter.format(bytesSent) + " Mb";
}
// giga bytes
else {
double bytesSent = bytes / (1024.0 * 1024.0 * 1024.0);
return formatter.format(bytesSent) + " Gb";
}
}
/**
* Formats bytes in a String representation in Kb.
*
* @param bytes The bytes.
* @return The String representation.
*/
public static String formatToKiloBytes(int bytes) {
double bytesSent = bytes / 1024.0;
if (bytesSent < 1.0) {
return "1 Kb";
} else {
return Long.toString(Math.round(bytesSent)) + " Kb";
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -