Reputation: 1578
I have a map which has file name as a key
in String
format and the contents as value
in bytearray
(byte[]).
I want to compress all the entries inside the map in a single tar file and convert the tar file into bytearray
without saving anything to the disk.
As of now I am creating the tar file in temp directory and again reading the tar file as byteArray.
But is there any other way which we can create a tar file in memory and convert it to bytearray ?
I am using appache commons TarArchive Library. this is what I tried so far..
TarArchiveOutputStream outTar = new TarArchiveOutputStream(byteArrayOutputStream);
for (Map.Entry<String, byte[]> entry : fileMap.entrySet()){
TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(entry.getKey());
tarArchiveEntry.setSize(entry.getValue().length);
try {
outTar.putArchiveEntry(tarArchiveEntry);
outTar.write(entry.getValue());
} catch (IOException e) {
e.printStackTrace();
}
}
try {
outTar.close();
outTar.closeArchiveEntry();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toByteArray();
Upvotes: 0
Views: 1323
Reputation: 8163
The closeArchiveEntry has to go into the for loop, you have to close each Entry before you begin the next:
for (Map.Entry<String, byte[]> entry : fileMap.entrySet()){
TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(entry.getKey());
tarArchiveEntry.setSize(entry.getValue().length);
try {
outTar.putArchiveEntry(tarArchiveEntry);
outTar.write(entry.getValue());
outTar.closeArchiveEntry(); //////// <-----------
} catch (IOException e) {
e.printStackTrace();
}
}
try {
outTar.close();
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 1