栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用Java将整数数组写入文件的最快方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用Java将整数数组写入文件的最快方法?

我看了三个选择:

  1. 使用
    DataOutputStream
    ;
  2. 使用
    ObjectOutputStream
    (对于
    Serializable
    对象而言
    int[]
    );和
  3. 使用
    FileChannel

结果是

DataOutputStream wrote 1,000,000 ints in 3,159.716 msObjectOutputStream wrote 1,000,000 ints in 295.602 msFileChannel wrote 1,000,000 ints in 110.094 ms

因此NIO版本是最快的。它还具有允许编辑的优点,这意味着您可以轻松更改一个int,而这

ObjectOutputStream
将需要读取整个数组,对其进行修改并将其写到文件中。

代码如下:

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<NUM_INTS; i++) {    ints[i] = r.nextInt();  }  time("DataOutputStream", new IntWriter() {    public void write(int[] ints) {      storeDO(ints);    }  }, ints);  time("ObjectOutputStream", new IntWriter() {    public void write(int[] ints) {      storeOO(ints);    }  }, ints);  time("FileChannel", new IntWriter() {    public void write(int[] ints) {      storeFC(ints);    }  }, ints);}private static void time(String name, IntWriter writer, int[] ints) {  long start = System.nanoTime();  writer.write(ints);  long end = System.nanoTime();  double ms = (end - start) / 1000000d;  System.out.printf("%s wrote %,d ints in %,.3f ms%n", name, ints.length, ms);}private static void storeOO(int[] ints) {  ObjectOutputStream out = null;  try {    out = new ObjectOutputStream(new FileOutputStream("object.out"));    out.writeObject(ints);  } catch (IOException e) {    throw new RuntimeException(e);  } finally {    safeClose(out);  }}private static void storeDO(int[] ints) {  DataOutputStream out = null;  try {    out = new DataOutputStream(new FileOutputStream("data.out"));    for (int anInt : ints) {      out.write(anInt);    }  } catch (IOException e) {    throw new RuntimeException(e);  } finally {    safeClose(out);  }}private static void storeFC(int[] ints) {  FileOutputStream out = null;  try {    out = new FileOutputStream("fc.out");    FileChannel file = out.getChannel();    ByteBuffer buf = file.map(FileChannel.MapMode.READ_WRITE, 0, 4 * ints.length);    for (int i : ints) {      buf.putInt(i);    }    file.close();  } catch (IOException e) {    throw new RuntimeException(e);  } finally {    safeClose(out);  }}private static void safeClose(OutputStream out) {  try {    if (out != null) {      out.close();    }  } catch (IOException e) {    // do nothing  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/463358.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号