【问题标题】:Write x bytes with value y to a file in java将值为y的x字节写入java中的文件
【发布时间】:2011-05-03 09:01:00
【问题描述】:

我正在尝试向文件写入一定数量的字节,比如说 x 字节,值为 y。问题是我做了很多时间,我目前正在使用 DataOutputStream 和 BufferedOutputStream 以及获取字节数组的 write 方法。每次我分配一个长度为 x 的新字节数组并写入它。这很浪费,我想知道是否有更有效的方法? 谢谢。

编辑:我通过分配一个随需求增长的大数组来实现它,但问题是我存储它并且它可能会变得非常大。 代码:

 byte[] block = new byte[4096];
    try {
        for(int i=0; i<nameOccurence.length; ++i){
            if(nameOccurence[i] >= block.length){
                int size = ((Integer.MAX_VALUE - nameOccurence[i]) <= 0.5*Integer.MAX_VALUE) ? Integer.MAX_VALUE : (nameOccurence[i] * 2);
                block = new byte[size];
            }
            if(nameOccurence[i] == 0){
                namePointer[i] = -1;//i.e. there are no vertices with this name
                continue;
            }
            namePointer[i] = byteCounter;

            ds.writeInt(nameOccurence[i]);
            ds.write(block, 0, nameOccurence[i]*2);
            ds.write(block, 0, nameOccurence[i]*2);
            byteCounter += (4*((long)nameOccurence[i]))+4;//because we wrote an integer.
        }

其中 ds 是 DataOutputStream。请注意,如果 nameOccurence[i] 足够大,数组块可以增长到 max int。

我认为最好的方法是在 nameOccurence 中的所有 i 上找到最大数量并分配此长度的数组。问题是它可以得到 Integer.MAX_VALUE。

也许循环运行并每次写入 1 个字节会更好?请注意DataOutputStream的底层是BufferedOutputStream。

【问题讨论】:

  • 请向我们展示您目前获得的代码。
  • 如果你重复写入相同的值,为什么你需要不止一个byte[]。如果您使用的是大型 byte[],为什么需要 BuffereOutputStream?
  • 您可以使用Arrays.fill() 填充byte[]。但除非这已被证明成为瓶颈,否则我不会在意。

标签: java io


【解决方案1】:

使用

String strFileName = "C:/FileIO/BufferedOutputStreamDemo";
FileOutputStream fos = new FileOutputStream(strFileName);
fos.write(yourbytes);

【讨论】:

  • 没关系,但我希望它更有效率,所以请阅读我的编辑。
【解决方案2】:

如果您不想每次都分配新数组,请分配一个绝对对您的 X 足够大的数组,将其存储在您的类中的某个位置,然后,当您需要编写它时,用 Y 填充它,并且您可以在OutputStream.write(byte[] b, int off, int len) 方法中指定要从数组中写入多少字节。此外,您不需要DataOutputStream 来写入字节,只需BufferedOutputStream 就足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 2011-10-13
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多