我只有几个小时的Java经验。
我想在for循环中的字节数组中存储一些信息。但是我需要知道什么时候它已满。如果它已满,我会将字节数组的内容写入输出文件并继续。我怎么知道呢?
这是我的代码:(数字只是一个例子,在我的实际代码中,它们来自某些计算)
byte[] wholeBlock =new byte[1024];
byte[] checkStorage= new byte[1000];
byte[] outputStore= new byte[60]; // when this is full I need to write it into file and erase content.
for(int i=0;i<256;i++){
if(wholeBlock[i]==checkStorage[i]){
// check if outputStore is full or not enough to store some number of bytes
// if there is enough space
// now I want to store 3 bytes starting from i'th member of checkStorage into outputStore. I also want to know how could I do that.
// otherwise
// write the content of outputStore into file
}
}
答案 0 :(得分:3)
要知道数组是如何“完整”的,你需要有一个“int counter”或类似的东西,并在每次向数组添加内容时增加它
答案 1 :(得分:2)
想象一下像一排盒子的数组,每个盒子都有一个定义类型的东西。
如果你要求一个数组outputStore = new byte[60]
,你会得到一个包含60个方框的行,每个方框的默认值为byte
类型(0b
})。
数组的问题是,程序总是满。它总是让所有的框都填充了一个字节,并且不能告诉你哪些框由默认填充,哪些框由你填充。
您有责任定义和存储该信息。并且通过维护int
类型的计数器或索引变量(或long
,如果int
不够大)来实现这一点。
作为初学者,您可能希望坚持使用数组来更好地理解Java原则。为此,您应该写出类似于以下内容的代码:
byte[] wholeBlock =new byte[1024];
byte[] checkStorage= new byte[1000];
byte[] outputStore= new byte[60]; // when this is full I need to write it into file and erase content.
int outputStoreIndex = 0;
for(int i=0;i<256;i++){ //do you mean to use wholeBlock.length or checkStorage.length?
if(wholeBlock[i]==checkStorage[i]){
// check if outputStore is full or not enough to store some number of bytes
// if there is enough space
if (outputStoreIndex < (outputStore.length-2)) { //the 2 accommodates i+2 below
// now I want to store 3 bytes starting from i'th member of checkStorage into outputStore
outputStore[outputStoreIndex] = checkStorage[i];
outputStore[outputStoreIndex+1] = checkStorage[i+1];
outputStore[outputStoreIndex+2] = checkStorage[i+2];
outputStoreIndex += 3;
// otherwise
} else {
// write the content of outputStore into file
/* here you can write the bytes */
//remember to write bytes from outputStore only up to (outputStoreIndex-1)
//to "erase" outputStore, simply reset the index to 0:
outputStoreIndex = 0;
}
}
}
随着Java越来越好,请探索其他人提到的选项,例如ArrayList
和ByteBuffer
。这些有助于减少调试应用程序所花费的时间,因为它们有助于自动化您使用阵列手动执行的操作。
答案 2 :(得分:0)
我的建议:nio包的ByteBuffer类
http://docs.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html
这里有一个例子
byte[] myByte = {1,1,1,1,1}; //5bytes
ByteBuffer buffer = ByteBuffer.allocate( 256 );
buffer.put(myByte);
System.out.println(buffer.capacity()); // it return 256
System.out.println(buffer.position()); // it return 5
buffer.put(myByte);
System.out.println(buffer.position()); // it return 10
System.out.println(buffer.remaining()); // it return 256 - 10
buffer.rewind();
System.out.println(buffer.position()); // it return 0