温馨提示×

java如何获取字节数

小亿
81
2024-09-26 01:17:18
栏目: 编程语言

在Java中,可以通过以下几种方法获取字节数:

  1. 获取字符串的字节数:
public static int getByteCount(String str) {
    if (str == null) {
        return 0;
    }
    return str.getBytes(StandardCharsets.UTF_8).length;
}

这里使用了StandardCharsets.UTF_8作为字符集,你可以根据需要更改为其他字符集。

  1. 获取文件的字节数:
import java.io.File;
import java.io.IOException;

public static long getByteCount(File file) {
    if (file == null || !file.exists()) {
        return 0;
    }
    try {
        return file.length();
    } catch (IOException e) {
        e.printStackTrace();
        return 0;
    }
}

这个方法返回文件的大小,单位为字节。

  1. 获取字节数组的长度:
public static int getByteCount(byte[] bytes) {
    if (bytes == null) {
        return 0;
    }
    return bytes.length;
}

这个方法返回字节数组的长度,单位为字节。

0