记磁盘与内存中整数占用字节数

137 阅读1分钟

磁盘

在磁盘中一个数字字符占1Byte(1字节),如下图:

image.png

image.png

内存

在JAVA中,一个整型(int)占4字节,将内存中的数写入磁盘时不为4字节,是一个字符一个字节。测试代码如下:

public class OutputStreamTest {
    public static void main(String[] args) {
        OutputStreamWriter os = null;
        Random random = new Random();
        try {
            os = new OutputStreamWriter(
                    new FileOutputStream(CommonStant.FILE_PATH), StandardCharsets.UTF_8);
            for (int i = 0; i < 4; i++) {
                for (int j =0; j < 1E9; j++){
                    os.write(1 + "");
                }
                System.out.println("A epoch finish");
                os.flush();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                assert os != null;
                os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

得到结果如下:

image.png

总结

在java中,内存中的int占4Bytes,磁盘中一个字符为1Byte

Tips

通过查看磁盘写入速率,计算写入时间大约为15S,计时15S左右发现完成一轮,理论正确。

a.png