0

I am using ZipOutputStream in an Android app to package and export mp3 files. The package and export appears to work fine, when the files are extracted, they are not playable. Running file command on the output shows the file type as data. Prior to zipping the file type is listed as Audio. Here's the code I'm using to compress the files:

 protected File compressFiles(File outputFile, File... inputFiles) {

    int bufferSize = 1024 * 4; // 4KB
    ZipOutputStream zipOutputStream = null;
    try {
        OutputStream fileOutputStream = new FileOutputStream(outputFile);
        zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
        int count = inputFiles.length;
        File file = null;
        for (int i = 0; i < inputFiles.length; i++) {
            file = inputFiles[i];

            String fileName = file.getName();
            ZipEntry entry = new ZipEntry(fileName);
            entry.setTime(file.lastModified());
            FileInputStream inputStream = new FileInputStream(file);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

            zipOutputStream.putNextEntry(entry);
            byte[] buffer = new byte[bufferSize];
            int bytesRead;
            while ((bytesRead = bufferedInputStream.read()) != -1) {
                zipOutputStream.write(buffer, 0, bytesRead);
            }

            zipOutputStream.closeEntry();
            inputStream.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (zipOutputStream != null) {
            try {
                zipOutputStream.finish();
               // zipOutputStream.flush();
                zipOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return outputFile;
}
Inn0vative1
  • 2,014
  • 3
  • 27
  • 43

1 Answers1

2

You are using the wrong overload of the BufferedInputStream.read() method.

You probably meant to pass in the byte[] buffer as a parameter, but instead, you didn't pass in any parameters. As a result you are only writing out zeroes from the buffer variable. In fact, even the bytesRead variable has the wrong value, as it returns the actual byte being read instead of the number of bytes.

To fix, simply change this line:

while ((bytesRead = bufferedInputStream.read()) != -1) {

to this:

while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
sstan
  • 35,425
  • 6
  • 48
  • 66