Java – ArrayList of arrays, how to make the size of the last array different from other arrays in the list
•
Java
Explain what I want to achieve:
I get a file. I have to read data from the file and create a block with a size of 1 KB For example, if the file size is 5.8 KB, I will have 5 blocks, 1 KB each, and the last block is 0.8 KB After having these in the block, I must perform Sha 256 encoding from the last block and attach it to the penultimate block, then I must apply the encoding to the penultimate block and attach it to the third block, and so on
problem
If I give more than 1024 bytes of file size, my code works well But if my last block size is not 1024, the code will not work as expected
The way I do this now is:
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); int sizeOfBlock = 1024; int sizeOfHash = 256; MessageDigest md; md = MessageDigest.getInstance("SHA-256"); byte[] block = new byte[sizeOfBlock]; List <byte []> blockList = new ArrayList <byte []>(); int tmp = 0; while ((tmp = bis.read(block)) > 0) { System.out.println(tmp); blockList.add(block); } for (int j = blockList.size()-1; j > 0;){ System.out.println(blockList.get(j).length); // for the first iteration it shouldnt be 1024 if the file size is not a multiple of 1024 md.update(blockList.get(j--)); byte[] hash = md.digest(); byte[] appendBlock = new byte[blockList.get(j).length + hash.length]; System.arraycopy(blockList.get(j),appendBlock,blockList.get(j).length); System.arraycopy(md.digest(),blockList.get(j).length,hash.length); blockList.set(j,appendBlock); } System.out.println(blockList.get(0).length); md.update(blockList.get(0)); byte[] hash = md.digest(); String result = bytesToHex(hash); // converting function from byte to hex System.out.println(result);
Solution
You seem to add the same 1024 byte array to the array list again and again
What you should do is as follows:
while ((tmp = bis.read(block)) > 0) { byte[] currentBlock = new byte[tmp]; System.arraycopy (block,currentBlock,tmp); System.out.println(tmp); blockList.add(currentBlock); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码