缓冲区位置无效

时间:2018-10-17 15:34:13

标签: java file

我的程序应将双打写入文件。结果应为具有1,000,000,000双精度的文件。但是由于某种原因,当文件变为2 GB时,错误崩溃,大约是250,000倍。

同时,她完美地创建了一个具有1亿和1亿双的文件 为什么会发生?

代码:

Mail

输出:

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;
import static java.nio.file.StandardOpenOption.*;
public class writeFileMapped {
    public static final int BUF_SIZE = 10000 * Double.BYTES;
    public static void main (String args[]){
        Random random = new Random();
        Path path = Paths.get("C:\\Users\\Den\\IdeaProjects\\semester_3\\src\\File_task\\test3.dat");
        try (FileChannel channel = FileChannel.open(path, CREATE, WRITE, READ)) {
            long startBubbleTime = System.currentTimeMillis();
            for (int i = 0; i < 1000000; i++) {
                MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, i * BUF_SIZE, BUF_SIZE);
                while (buf.hasRemaining()) {
                    double d = random.nextDouble();
                    buf.putDouble(d);
                }
                channel.read(buf);
            }
            long endBubbleTime = System.currentTimeMillis();
            System.out.println(endBubbleTime-startBubbleTime);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

18个字符串= MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE,i * BUF_SIZE,BUF_SIZE);

1 个答案:

答案 0 :(得分:0)

根据我调试的结果,您的位置在-2147447296中崩溃,这意味着它是整数的最大值,只需将int更改为longs

public static final long BUF_SIZE = 10000 * Double.BYTES;

for (long i = 0; i < 1000000; i++)

当您乘以头寸时,您可能还想将其强制转换为很长的时间,我已经将文件保存到4GB,然后停止了程序