Write Tar File of Unknown (Large) Size in Java

℡╲_俬逩灬. 提交于 2019-12-21 03:34:19

问题


I'd like to write a large stream of unknown size to a tar file in Java. I know that Apache has the commons compress library which handles tar files, but they require me to know the size in advance. Consider Apache's own example:

TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setSize(size);
tarOutput.putArchiveEntry(entry);
tarOutput.write(contentOfEntry);
tarOutput.closeArchiveEntry();

I will know the size of the entry after I write it, but not before. Isn't there a way that I can write the content and when I finish the size is then written to the header?


回答1:


I ended up taking jtar and modifying it so you don't have to specify the size until after you write. It seems there is no package that does this natively... I set up an issue that requests this change. Unfortunately, it required a lot of ugly code and creating my own RandomAccessFileInputStream(), which is unsuitable for uploading a patch.




回答2:


If you have only one text file to be added then you can use setSize(long) method and set the size of the entry.

where data is string which you want to be tarred.

long size=data.getByte().length;
TarArchiveEntry entry = new TarArchiveEntry("sample.txt");
entry.setSize(size);
tarOutput.putArchiveEntry(entry);
tarOutput.write(contentOfEntry);
tarOutput.closeArchiveEntry();


来源:https://stackoverflow.com/questions/10501045/write-tar-file-of-unknown-large-size-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!