![](/img/trans.png)
[英]Why does my ArrayList contain N copies of the last item added to the list?
[英]Why does my untar not contain the last bytes
我已經編寫了一個用於.tar.gz
文件的rest資源。 一切正常。 我嘗試過請求它,保存數據,解tar xzvf [filename]
(使用tar xzvf [filename]
),然后我得到了正確的數據。
但是,我試圖使用java.util.zip.GZIPInputStream
和org.apache.tools.tar.TarInputStream
解壓縮並解壓縮我在JUnit測試中提供的.tar.gz
,以驗證其是否自動運行。 這是我的單元測試中的代碼,其中刪除了一些詳細信息:
HttpResponse response = <make request code here>
byte[] receivedBytes = FileHelper.copyInputStreamToByteArray(response.getEntity().getContent(), true);
GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(receivedBytes));
TarInputStream tarInputStream = new TarInputStream(gzipInputStream);
TarEntry tarEntry = tarInputStream.getNextEntry();
ByteArrayOutputStream byteArrayOutputStream = null;
System.out.println("Record size: " + tarInputStream.getRecordSize());
while (tarEntry != null) // It only goes in here once
{
byteArrayOutputStream = new ByteArrayOutputStream();
tarInputStream.copyEntryContents(byteArrayOutputStream);
tarEntry = tarInputStream.getNextEntry();
}
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
byte[] archivedBytes = byteArrayOutputStream.toByteArray();
byte[] actualBytes = <get actual bytes>
Assert.assertArrayEquals(actualBytes, archivedBytes);
最終斷言失敗,字節X = (n * 512) + 1
處存在差異,其中n
是最大自然數,因此n * 512 <= l
, l
是數據長度。 也就是說,我正確地獲得了512字節數據的最大可能倍數,但是調試測試后,我可以看到所有剩余字節均為零。 因此,如果數據總量為1000個字節,則archivedBytes
中的前512個字節是正確的,但后488個都為零/未設置,並且如果總數據為262272個字節,我將獲得前262144個(512 * 512)字節正確,但剩余字節再次全部為零。
另外,上面的tarInputStream.getRecordSize()
系統打印出Record size: 512
,所以我認為這與某種原因有關。 但是,由於如果我下載該歸檔文件,則可以正常工作,因此我猜數據必須存在,並且只是缺少一些內容。
進入具有1000字節數據的tarInputStream.copyEntryContents(byteArrayOutputStream)
,在
int numRead = read(buf, 0, buf.length);
numRead
為100,但查看緩沖區,只有前512個字節為非零。 也許我不應該使用該方法從TarInputStream
獲取數據?
如果有人知道它應該如何工作,我將非常感謝您提供任何建議或幫助。
您可以指定創建tar歸檔文件時要使用的輸出塊大小。 因此,存檔的大小將是塊大小的倍數。 由於檔案大小通常無法容納全部塊,因此將零添加到最后一個數據塊以使其具有正確的大小。
原來,我錯在我原來的問題,錯誤是在資源的代碼。 寫入時,我沒有關閉TarOutputStream上的條目。 我想這在從服務器手動請求它時不會引起任何問題,也許是因為該條目是用連接或其他東西關閉的,但是在從單元測試中請求時卻以不同的方式工作……盡管我必須承認這樣做並沒有很有意思的是:P
查看下面的代碼片段,我缺少第3行。
1: tarOutputStream.putNextEntry(tarEntry);
2: tarOutputStream.write(fileRawBytes);
3: tarOutputStream.closeEntry();
4: tarOutputStream.close();
我什至不知道TarOutputStream上有諸如“ closeEntry”之類的東西……我現在要做! :P
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.