如何在不使用java中的zipfile条目的情况下将包含xml的zip文件转换为字节数组

时间:2014-03-27 09:56:28

标签: web-services bytearray file-transfer zipfile

我有一个包含在Java中生成的xml文件的zip文件。我将以字节数组格式将zip文件发送到Web服务。将zip文件转换为字节数组的代码片段是

public static byte[] FileToArrayOfBytes(ZipFile file) throws IOException {

         final Enumeration<? extends ZipEntry> entries = file.entries();
         final ZipEntry entry = entries.nextElement();

         BufferedInputStream istream = new BufferedInputStream(
                       file.getInputStream(entry));
         int file_size       = (int) entry.getCompressedSize();
         byte[] blob = new byte[file_size];
         int bytes_read      = 0;
         int offset          = 0;

         while ((bytes_read = istream.read(blob, 0, file_size)) != -1) {
                offset += bytes_read;
         }

         file.close();
         istream.close();

         return blob;
   }

当我发送从上面的方法返回的字节数组时,Web服务返回错误消息为“无效的文件扩展名”。通常我们知道Web服务接受zip文件。

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我按照以下方式处理了我的问题

public static byte[] convertFileIntoArrayOfBytes(String zipFilePath) {

    FileInputStream fileInputStream = null;

    File file = new File(zipFilePath);

    byte[] bFile = new byte[(int) file.length()];

    try {
        // convert file into array of bytes
        fileInputStream = new FileInputStream(zipFilePath);
        fileInputStream.read(bFile);
        fileInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bFile;
}