微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从ByteArrayOutputStream创建文件

如何解决从ByteArrayOutputStream创建文件

我正在尝试从ByteArrayOutputStream创建单独的文件(这里byteOut是我的ByteOutputStream)。以下代码可以完成

        final InputStream targetStream = new ByteArrayInputStream(byteOut.toByteArray());
        final File destDir = new File(System.getProperty("user.dir"));
        final byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(targetStream);
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            File newFile = new File(destDir,zipEntry.getName());
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer,len);
            }
            fos.close();
            zipEntry = zis.getNextEntry();
        } 

但是我想优化代码,我尝试像这样使用IoUtils.copy

        final InputStream targetStream = new ByteArrayInputStream(byteOut.toByteArray());
        final File destDir = new File(System.getProperty("user.dir"));
        ZipInputStream zis = new ZipInputStream(targetStream);
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            File newFile = new File(destDir,zipEntry.getName());
            try(InputStream is = new FileInputStream(newFile);
                    OutputStream fos = new FileOutputStream(newFile)) {
                IoUtils.copy(is,fos);
            }
            zipEntry = zis.getNextEntry();
        }

但是文件内容没有被复制,在第二次迭代中我也得到了FileNotFoundException。我在做什么错了?

解决方法

这是更通用的Path&Files类的用例。使用zip文件系统,它将成为高级复制。

    Map<String,String> env = new HashMap<>(); 
    //env.put("create","true");
    URI uri = new URI("jar:file:/foo/bar.zip");       
    FileSystem zipfs = FileSystems.newFileSystem(uri,env);

    Path targetDir = Paths.get("C:/Temp");

    Path pathInZip = zipfs.getPath("/");
    Files.list(pathInZip)
         .forEach(p -> {
             Path targetP = Paths.get(targetDir,p.toString();
             Files.createDirectories(targetP.getParent());
             Files.copy(p,targetP);
         }); 

使用基础Input / OutputStream必须确保is没有关闭,并还原到库(IOUtils)/ InputStream.transferTo(OutputStream)以及所有这些详细信息。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。