2011-05-03 21 views
1

我正在尝试写入文件的某个字节数为x字节,其值为y。问题是我做了很多时间,而且我正在使用带有BufferedOutputStream的DataOutputStream以及获取字节数组的写入方法。每次我分配一个长度为x的新字节数组并写入它。这是浪费,我不知道是否有更有效的方法? 谢谢。用值y将x字节写入java中的文件

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

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中查找所有我的最大数字并分配这个长度的数组。问题是它可以获得Integer.MAX_VALUE。

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

+2

请告诉我们你走到这一步的代码。 – asgs 2011-05-03 09:03:43

+2

如果你反复写入相同的值,为什么你需要多一个'byte []'。如果你使用一个大的byte []'为什么你需要一个BuffereOutputStream? – 2011-05-03 09:06:30

+1

您可以使用['Arrays.fill()'](http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#fill(byte [],%20byte))填充'byte []'。但除非**被证明**是一个瓶颈,否则我不会在乎。 – 2011-05-03 09:16:02

回答

3

使用

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

它确定,但我希望它更有效率,所以请阅读我的编辑。 – 2011-05-03 11:09:19

1

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