无法从ZipInputStream字节数组中在Oracle中写入映像

时间:2013-05-28 03:31:22

标签: java spring java-ee jpa

我从SO中按照几个例子从zip获取图像文件,并将每个文件字节放入一个hashmap:

final byte[] zip_file = ((CommonsMultipartFile) zip_file).getBytes();
zip_stream = new ZipInputStream(new ByteArrayInputStream(zip_file));

try {
    while ((entry = zip_stream.getNextEntry()) != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            BufferedOutputStream dest = new BufferedOutputStream(baos, BUFFER_SIZE);
                try {
                    int count = 0;
                    byte[] data = new byte[BUFFER_SIZE];

                    while ((count = zip_stream.read(data, 0, BUFFER_SIZE)) > 0) {
                        dest.write(data, 0, count);
                    }

                    dest.flush();

                    filelist.put(entry.getName(), baos.toByteArray());
                    baos.reset();
                } finally {
                    dest.close();
                }
            } finally {
                baos.close();
            }
        }
    } finally {
        zip_stream.close();
    }

稍后从filelist读取时,字节数组将持久存储到java bean中,就像这样

Customer customer = new Customer();
byte[] image = fileist.get(imageFileName);
customer.setImage(image);

Customer是一个JPA实体,字段image的{​​{1}}类型。所以这部分应该没有任何问题。

悲伤的一方是在整个事务之后有一些数据写入'image'字段但是从Oracle(使用SQL开发人员)字节无法组成图像文件,这意味着从oracle文件被破坏。必须有错误使字节损坏。我怎样才能使它发挥作用?

更新

使用@Lob更改输入流 - 输出流传输但仍无法正常工作......但我觉得这里有问题,但不知道如何修复。 在下面的代码中,循环似乎对zipInputStream的每个条目起作用,从不访问条目而不是文件名,它看起来是否正常

IOUtils.copy

1 个答案:

答案 0 :(得分:1)

删除baos.set并在baos.close之后移动filelist.put。

老实说,我认为应该反向嵌套dest和baos,并且dest.close应该足够,意味着关闭baos。

也可以使用getInputStream来代替getBytes。

当然IOUtils有一个copy;应该有一个带有“保持打开状态”标志的副本。


未跳过目录条目,并且未调用closeEntry。

    try {
        ZipInputStream zipInputStream = new ZipInputStream(
            new FileInputStream("D:/dev/... .zip"));
        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            System.out.println("- " + zipEntry.getName()
                + " #" + zipEntry.getSize());
            if (zipEntry.isDirectory()) {
                zipInputStream.closeEntry();
                continue;
            }

            long size = zipEntry.getSize();
            if (size > Integer.MAX_VALUE) {
                throw new IOException("File too large: " + zipEntry.getName());
            }
            int reserved = size == -1L ? 8192 : (int)size; 
            ByteArrayOutputStream baos = new ByteArrayOutputStream(reserved);
            IOUtils.copy(zipInputStream, baos);
            zipInputStream.closeEntry();

            baos.close();
            File file = new File("D:/dev/data/temp/" + zipEntry.getName());
            file.getParentFile().mkdirs();
            FileUtils.writeByteArrayToFile(file, baos.toByteArray());
        }
    } catch (IOException ex) {
        Logger.getLogger(Stackoverflow.class.getName()).log(Level.SEVERE, null, ex);
    }
相关问题