Fastest way to write an array of integers to a file in Java?

前端 未结 6 501
小鲜肉
小鲜肉 2020-12-05 08:33

As the title says, I\'m looking for the fastest possible way to write integer arrays to files. The arrays will vary in size, and will realistically contain anywhere between

6条回答
  •  时光说笑
    2020-12-05 08:59

    I had a look at three options:

    1. Using DataOutputStream;
    2. Using ObjectOutputStream (for Serializable objects, which int[] is); and
    3. Using FileChannel.

    The results are

    DataOutputStream wrote 1,000,000 ints in 3,159.716 ms
    ObjectOutputStream wrote 1,000,000 ints in 295.602 ms
    FileChannel wrote 1,000,000 ints in 110.094 ms
    

    So the NIO version is the fastest. It also has the advantage of allowing edits, meaning you can easily change one int whereas the ObjectOutputStream would require reading the entire array, modifying it and writing it out to file.

    Code follows:

    private static final int NUM_INTS = 1000000;
    
    interface IntWriter {
      void write(int[] ints);
    }
    
    public static void main(String[] args) {
      int[] ints = new int[NUM_INTS];
      Random r = new Random();
      for (int i=0; i

提交回复
热议问题