我正在尝试将一定数量的字节写入文件,比如 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 是数据输出流。请注意,如果 nameOccurence[i] 足够大,数组 block 可以增长到 max int。
我认为最好的方法是找到 nameOccurence 中所有 i 的最大数量并分配这个长度的数组。问题是它可以获得 Integer.MAX_VALUE。
也许循环运行并每次写入1个字节会更好?请注意DataOuputStream的底层是BufferedOutputStream。
最佳答案
使用
String strFileName = "C:/FileIO/BufferedOutputStreamDemo";
FileOutputStream fos = new FileOutputStream(strFileName);
fos.write(yourbytes);
关于java - 将值为 y 的 x 个字节写入 java 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5867297/