Java 格式化文件大小为B、K、M、G

本文介绍了一个用于将文件大小从字节转换为更易读格式(如KB、MB、GB)的Java工具类。通过使用1024作为进制,该工具类能将原始字节数转换成带单位的字符串形式,方便用户理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工作中遇到图片、音视频、文档等文件管理业务或数据流量统计业务时,文件大小或数据流量大小属性常以byte 数据为存储单位,存储和排序等都好操作。然而在前端展示给用户时,该数据却并不友好,因此,需要将文件大小适当转换,以便用户阅读。

以下代码以 1024 为进制,封装了一个工具类 FileSizeUtil

代码

FileSizeUtil 代码如下:

import java.text.DecimalFormat;
import java.util.Objects;

/**
 * 文件大小工具类
 * <div>数据存储转换,最大支持到G</div>
 * @author xzbd
 *
 */
public class FileSizeUtil {
	public static final Integer K_SIZE = 1024;

	public static final Integer M_SIZE = 1048576;

	public static final Integer G_SIZE = 1073741824;

	public static final String B = "B";

	public static final String K = "K";

	public static final String M = "M";

	public static final String G = "G";

	/**
	 * 将字节数据转为带单位的字符串
	 * 
	 * @param fileSize 文件字节大小
	 * @return
	 */
	public static String formatFileSize(Long fileSize) {
		String fileSizeStr = "";
		if (Objects.isNull(fileSize)) {
			return fileSizeStr;
		}
		if (fileSize == 0L) {
			return "0".concat(B);
		}
		DecimalFormat df = new DecimalFormat("#.00");
		if (fileSize < K_SIZE) {
			fileSizeStr = df.format((double) fileSize) + B;
		} else if (fileSize < M_SIZE) {
			fileSizeStr = df.format((double) fileSize / K_SIZE) + K;
		} else if (fileSize < G_SIZE) {
			fileSizeStr = df.format((double) fileSize / M_SIZE) + M;
		} else {
			fileSizeStr = df.format((double) fileSize / G_SIZE) + G;
		}
		return fileSizeStr;
	}
}

注:
有些场景中 数据大小的单位进率并不以 1024 计算,而是使用 1000 来计算,此种情况,请修改 K_SIZE 、 M_SIZE 、G_SIZE 的值即可。

以下是用Java编写的哈夫曼编码实现: HuffmanNode.java ```java public class HuffmanNode implements Comparable<HuffmanNode> { char ch; int freq; HuffmanNode left, right; public HuffmanNode(char ch, int freq, HuffmanNode left, HuffmanNode right) { this.ch = ch; this.freq = freq; this.left = left; this.right = right; } public boolean isLeaf() { return left == null && right == null; } @Override public int compareTo(HuffmanNode o) { return freq - o.freq; } } ``` HuffmanTree.java ```java import java.io.*; import java.util.*; public class HuffmanTree { private HuffmanNode root; public void initialize() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // 读入字符集大小和字符频率 int n = Integer.parseInt(reader.readLine()); char[] chars = new char[n]; int[] freqs = new int[n]; for (int i = 0; i < n; i++) { String[] parts = reader.readLine().split(" "); chars[i] = parts[0].charAt(0); freqs[i] = Integer.parseInt(parts[1]); } // 建立哈夫曼树 PriorityQueue<HuffmanNode> pq = new PriorityQueue<>(); for (int i = 0; i < n; i++) { pq.offer(new HuffmanNode(chars[i], freqs[i], null, null)); } while (pq.size() > 1) { HuffmanNode left = pq.poll(); HuffmanNode right = pq.poll(); pq.offer(new HuffmanNode('\0', left.freq + right.freq, left, right)); } root = pq.poll(); // 将哈夫曼树存入文件 try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("hfmTree"))) { out.writeObject(root); } } public void encoding() throws IOException, ClassNotFoundException { // 读入哈夫曼树 try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("hfmTree"))) { root = (HuffmanNode) in.readObject(); } // 编码文本文件 BufferedReader reader = new BufferedReader(new FileReader("ToBeTran")); BitOutputStream out = new BitOutputStream(new FileOutputStream("CodeFile")); String line; while ((line = reader.readLine()) != null) { for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); String code = getCode(ch); for (int j = 0; j < code.length(); j++) { out.writeBit(code.charAt(j) == '1' ? 1 : 0); } } } reader.close(); out.close(); } public void decoding() throws IOException, ClassNotFoundException { // 读入哈夫曼树 try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("hfmTree"))) { root = (HuffmanNode) in.readObject(); } // 译码代码文件 BitInputStream in = new BitInputStream(new FileInputStream("CodeFile")); BufferedWriter writer = new BufferedWriter(new FileWriter("TextFile")); HuffmanNode node = root; while (true) { int bit = in.readBit(); if (bit < 0) break; if (bit == 0) node = node.left; else node = node.right; if (node.isLeaf()) { writer.write(node.ch); node = root; } } in.close(); writer.close(); } public void printingCodeFile() throws IOException { BufferedReader reader = new BufferedReader(new FileReader("CodeFile")); BufferedWriter writer = new BufferedWriter(new FileWriter("CodePrin")); int count = 0; int c; while ((c = reader.read()) != -1) { writer.write(c); count++; if (count == 50) { writer.newLine(); count = 0; } } reader.close(); writer.close(); } public void printingHuffmanTree() throws IOException, ClassNotFoundException { // 读入哈夫曼树 try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("hfmTree"))) { root = (HuffmanNode) in.readObject(); } // 打印哈夫曼树 BufferedWriter writer = new BufferedWriter(new FileWriter("TreePrint")); printHuffmanTree(root, "", writer); writer.close(); } private String getCode(char ch) { StringBuilder sb = new StringBuilder(); getCode(root, ch, sb); return sb.toString(); } private void getCode(HuffmanNode node, char ch, StringBuilder sb) { if (node == null) return; if (node.isLeaf() && node.ch == ch) return; if (node.left != null) { getCode(node.left, ch, sb); if (sb.length() > 0) sb.append('0'); } if (node.right != null) { getCode(node.right, ch, sb); if (sb.length() > 0) sb.append('1'); } if (sb.length() > 0 && sb.charAt(sb.length() - 1) != '0') sb.deleteCharAt(sb.length() - 1); } private void printHuffmanTree(HuffmanNode node, String indent, BufferedWriter writer) throws IOException { if (node == null) return; writer.write(indent); if (node.isLeaf()) { writer.write(node.ch + "\n"); } else { writer.write("-\n"); printHuffmanTree(node.left, indent + " |", writer); printHuffmanTree(node.right, indent + " ", writer); } } private static class BitOutputStream { private OutputStream out; private int buffer; private int count; public BitOutputStream(OutputStream out) { this.out = out; buffer = 0; count = 0; } public void writeBit(int bit) throws IOException { buffer <<= 1; if (bit == 1) buffer |= 1; count++; if (count == 8) { out.write(buffer); buffer = 0; count = 0; } } public void close() throws IOException { if (count > 0) { buffer <<= (8 - count); out.write(buffer); } out.close(); } } private static class BitInputStream { private InputStream in; private int buffer; private int count; public BitInputStream(InputStream in) { this.in = in; buffer = 0; count = 0; } public int readBit() throws IOException { if (count == 0) { buffer = in.read(); if (buffer < 0) return -1; count = 8; } int bit = (buffer >> (count - 1)) & 1; count--; return bit; } public void close() throws IOException { in.close(); } } } ``` Main.java ```java import java.io.IOException; public class Main { public static void main(String[] args) throws IOException, ClassNotFoundException { HuffmanTree huffmanTree = new HuffmanTree(); huffmanTree.initialize(); huffmanTree.encoding(); huffmanTree.decoding(); huffmanTree.printingCodeFile(); huffmanTree.printingHuffmanTree(); } } ``` 测试数据: 输入: ``` 26 A 186 B 64 C 13 D 22 E 32 F 103 G 21 H 15 I 47 J 57 K 1 L 5 M 32 N 57 O 63 P 15 Q 1 R 48 S 51 T 80 U 23 V 8 W 18 X 1 Y 16 ``` 输出: CodePrin: ``` 0000000000000000000000000000000000000000001001000000000011110101000000000001000000000011010000010001010000000000010001000000000000000000100000110100110001000000000000100000000000000000000010010010 01000000000000000100000000000000000000000000000000001001000000000001000101010000000100000000000000000000000101100001000001000000010000000000000000000000000000000001000000000010100000000000110100 0000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000100000000001010000000000000000010100000000000000000000000000000000000000000000000000000000000000 0000100100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ``` TextFile: ``` THIS PROGRAM IS MY FAVORITE ``` TreePrint: ``` - | A | - | - | B | - | C | - | D | - | E | - - | G | - - | H | - - | I | - - | J | - - | - | M | - - | - | N | - | O | - | P | - - | - | Q | - - | R | - | S | - | T | - | - | V | - - | W | - | X | - - | Y | - ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值