Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
here is my code:
final InputStream inputStream = MY_RECEIVED_INPUT_STREAM;
ZipInputStream zis = new ZipInputStream(inputStream);
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
zipEntry = zis.getNextEntry();
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
zis.closeEntry();
zis.close();
I receive zip file with many files inside. I want to write these files to database. What I want is to get bytes from each and every ZipEntry and save them to database as Blob (xxxxxx.... part).
How can I get bytes from zipEntry?
I don't have ZipFile, so I can't use something like this:
InputStream stream = zipFile.getInputStream(entry);
byte[] bytes = IOUtils.readAllBytes(zipFile.getInputStream(entry));
Thanks in advance.
You can use something like this:
InputStream is = MY_RECEIVED_INPUT_STREAM;
BufferedInputStream bis = null;
ZipInputStream zis = null;
ByteArrayOutputStream out = null;
String name = null;
byte[] b = new byte[8192];
int len = 0;
try {
bis = new BufferedInputStream(is);
zis = new ZipInputStream(bis);
ZipEntry zipEntry = null;
while ((zipEntry = zis.getNextEntry()) != null) {
//name of file
name = zipEntry.getName();
if (zipEntry.isDirectory()) {
//I'm skipping directories in this example
continue;
out = new ByteArrayOutputStream();
while ((len = zis.read(b)) > 0) {
out.write(b, 0, len);
//save to DB - db_save(String file_name, byte[] file_bytes)
db_save(name,out.toByteArray());
out.close();
} finally {
if (zis != null) {
zis.close();
if (bis != null) {
bis.close();
if (is != null) {
is.close();
–
ZipFile
makes this easier to read but the basic rule is that the ZipInputStream
is lined up to the content relating to the current ZipEntry
.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/zip/ZipInputStream.html#read(byte%5B%5D,int,int)
Read directly from zis
until 0 and don't close()
until all entries are handled.
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
// xxx Do BLOB creation
zis.transferTo(outputStream); // Java9
(PS You don't need to call closeEntry()
)
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.