mp3 上的 ZipOutputStream 损坏文件 - 创建数据文件而不是音频文件

ZipOutputStream on mp3 corrupts files - Creates data files not audio files

我在 Android 应用程序中使用 ZipOutputStream 来打包和导出 mp3 文件。打包和导出似乎工作正常,当文件被提取时,它们无法播放。 运行 file 命令的输出显示文件类型为 data。在压缩之前,文件类型列为 Audio。 这是我用来压缩文件的代码:

 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;
}

您使用了错误的 BufferedInputStream.read() 方法重载。

您可能打算将 byte[] buffer 作为参数传入,但您没有传入任何参数。因此,您只是从 buffer 变量中写出零。事实上,即使 bytesRead 变量也有错误的值,因为它 returns 实际读取的字节而不是字节数。

要修复,只需更改此行:

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

对此:

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