3

The Apache Commons compress library seems focused around writing a TarArchiveEntry to TarArchiveOutputStream. But it looks like the only way to create a TarArchiveEntry is with a File object.

I don't have files to write to the Tar, I have byte[]s in memory or preferably streams. And I don't want to write a bunch of temp files to disk just so that I can build a tar.

Is there any way I can do something like:

TarEntry entry = new TarEntry(int size, String filename);
entry.write(byte[] fileContents);
TarArchiveOutputStream tarOut = new TarArchiveOutputStream();
tarOut.write(entry);
tarOut.flush();
tarOut.close();

Or, even better....

InputStream nioTarContentsInputStream = .....
TarEntry entry = new TarEntry(int size, String filename);
entry.write(nioTarContentsInputStream);
TarArchiveOutputStream tarOut = new TarArchiveOutputStream();
tarOut.write(entry);
tarOut.flush();
tarOut.close();
AstroCB
  • 12,337
  • 20
  • 57
  • 73
MeowCode
  • 1,053
  • 2
  • 12
  • 29

1 Answers1

6

Use the following code:

byte[] test1Content = new byte[] { /* Some data */ }; 

TarArchiveEntry entry1 = new TarArchiveEntry("test1.txt");
entry1.setSize(test1Content.length);

TarArchiveOutputStream out = new TarArchiveOutputStream(new FileOutputStream("out.tar"));
out.putArchiveEntry(entry1);
out.write(test1Content);
out.closeArchiveEntry();
out.close();

This builds the desired tar file with a single file in it, with the contents from the byte[].

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
MeowCode
  • 1,053
  • 2
  • 12
  • 29