简体   繁体   English

从 ByteArrayOutputStream 创建文件

[英]Creating files from ByteArrayOutputStream

I am trying to create separate files from ByteArrayOutputStream (Here byteOut is my ByteOutputStream).我正在尝试从 ByteArrayOutputStream 创建单独的文件(这里的 byteOut 是我的 ByteOutputStream)。 The following code does the job下面的代码完成了这项工作

        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, 0, len);
            }
            fos.close();
            zipEntry = zis.getNextEntry();
        } 

But I want to optimize the code, I tried using IOUtils.copy like this但是我想优化代码,我试过像这样使用 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();
        }

But the contents of the file aren't getting copied and I also get a FileNotFoundException in the second iteration.但是文件的内容没有被复制,我在第二次迭代中也得到了 FileNotFoundException。 What am I doing wrong?我究竟做错了什么?

This is a use-case for the more generalized Path & Files classes.这是更通用的路径和文件类的用例。 With a zip file system it becomes a high level copying.使用 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);
         }); 

Using the underlying Input/OutputStream one must ensure that is is not closed, revert to a library (IOUtils) / InputStream.transferTo(OutputStream) and all those details.使用底层的 Input/OutputStream 必须确保is关闭,恢复到库 (IOUtils) / InputStream.transferTo(OutputStream) 和所有这些细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM