java解决超大二维矩阵数组引起的内存占用过大问题

内存咱不行,咱换磁盘,吃磁盘IO

这里文件一定要删除,不然写入数据会有脏数据问题,他不会清除之前已有的数据。还有就是他的存储量也有上限单个文件2GB

这里我用了一个10000*10000的数组弄了点模拟值,画了个图,完美的解决了我们之前矩阵过大无法计算的问题

public static void main(String[] args) throws Exception {
    Date date = new Date();
    File file = new File("C:\\Users\\Desktop\\临时文件\\a");
    file.delete();
    file.createNewFile();
    MMF mmf = new MMF(10000, 10000, "C:\\Users\\18833\\Desktop\\临时文件\\a");
    for (int i = 1500; i < 2000; i++) {
        System.out.println("存入数组" + i);
        for (int j = 1500; j < 2000; j++) {
            mmf.set(i, j, 255);
        }
    }
    int width = 10000;
    int height = 10000;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = image.createGraphics();
    for (int i = 0; i < 10000; i++) {
        System.out.println("画入指定位置" + i);
        for (int j = 0; j < 10000; j++) {
            if (mmf.get(i, j) != 0) {
                image.setRGB(i, j, Color.red.getRGB());
            }
        }
    }
    g2d.dispose();
    try {
        ImageIO.write(image, "png", new File("C:\\Users\\Desktop\\临时文件\\output.png"));
    } catch (IOException e) {
        System.err.println("保存图片时出错: " + e.getMessage());
    }
    System.out.println("耗时:"+(new Date().getTime() - date.getTime())/1000);
}
package com.hydf.upar.service;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MMF {
    private final int rows;
    private final int cols;
    private final MappedByteBuffer buffer;

    public MMF(int rows, int cols, String path) throws Exception {
        this.rows = rows;
        this.cols = cols;
        try (RandomAccessFile file = new RandomAccessFile(path, "rw")) {
            long size = (long) rows * cols * Integer.BYTES;
            buffer = file.getChannel().map(
                    FileChannel.MapMode.READ_WRITE, 0, size
            );
        }
    }

    public int get(int row, int col) {
        int pos = (row * cols + col) * Integer.BYTES;
        return buffer.getInt(pos);
    }

    public void set(int row, int col, int value) {
        int pos = (row * cols + col) * Integer.BYTES;
        buffer.putInt(pos, value);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

I'm the future

希望有幸帮到解决问题

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值