从bytearrayoutputstream创建文件

46scxncf  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(478)

我试图从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, 0, 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。我做错什么了?

arknldoa

arknldoa1#

这是更通用的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);
         });

使用底层输入/输出流必须确保 is 如果未关闭,请还原到库(ioutils)/inputstream.transferto(outputstream)和所有这些详细信息。

相关问题