内存咱不行,咱换磁盘,吃磁盘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);
}
}