1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java代码-zip解压不可预料的压缩文件末端一级压缩包中的文件为0kb以及目录创建流会报错

java代码-zip解压不可预料的压缩文件末端一级压缩包中的文件为0kb以及目录创建流会报错

时间:2023-02-19 12:07:24

相关推荐

java代码-zip解压不可预料的压缩文件末端一级压缩包中的文件为0kb以及目录创建流会报错

这几种错一般都是未关闭或者流的关闭顺序不对,可以使用try-resource

"D:\\huangzhengfile\\pretmp\\files\\wisdomAudit\\upload";是一级目录,该目录下全是文件哦

解压之后第一个文件或者最后一个文件是0kb,错误代码:

@Testvoid test4() throws FileNotFoundException {String name = "D:\\huangzhengfile\\pretmp\\files\\wisdomAudit\\upload";File file = new File(name);ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("D:\\huangzhengfile\\pretmp\\wwww.zip"));if (file.isDirectory()) {for (File file1 : file.listFiles()) {try (FileInputStream in = new FileInputStream(file1)) {zipOut.putNextEntry(new ZipEntry(file1.getName()));int temp;byte[] bytes = new byte[1024];while ((temp = in.read(bytes)) != -1) {zipOut.write(bytes, 0, temp);}} catch (IOException ex) {ex.printStackTrace();}}}else {try (FileInputStream in = new FileInputStream(file)) {zipOut.putNextEntry(new ZipEntry(file.getName()));int temp;byte[] bytes = new byte[1024];while ((temp = in.read(bytes)) != -1) {zipOut.write(bytes, 0, temp);}} catch (Exception e) {e.printStackTrace();}finally {IOUtils.closeQuietly(zipOut);}}}

实在找不出问题在哪儿,最后将想到可能是流的关闭顺序,然后就ok了

代码改进:

@Testvoid test1() {String name = "D:\\huangzhengfile\\pretmp\\files\\wisdomAudit\\upload";try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("D:\\huangzhengfile\\pretmp\\wwww.zip"))) {File file = new File(name);if (file.isDirectory()) {for (File file1 : file.listFiles()) {try (FileInputStream in = new FileInputStream(file1)) {zipOut.putNextEntry(new ZipEntry(file1.getName()));int temp;byte[] bytes = new byte[1024];while ((temp = in.read(bytes)) != -1) {zipOut.write(bytes, 0, temp);}} catch (IOException ex) {ex.printStackTrace();}}}else{try (FileInputStream in = new FileInputStream(file)) {zipOut.putNextEntry(new ZipEntry(file.getName()));int temp;byte[] bytes = new byte[1024];while ((temp = in.read(bytes)) != -1) {zipOut.write(bytes, 0, temp);}} catch (Exception e) {e.printStackTrace();}}}catch (Exception e){e.getMessage();}}

使用目录作为流汇报错,如下,所以代码之后判断为文件在使用流

@Testvoid test3() throws FileNotFoundException {String name = "D:\\huangzhengfile\\pretmp\\files\\wisdomAudit\\upload";File file = new File(name);FileInputStream fileinputStream = new FileInputStream(name);//会报错,目录创建流的时候汇报错System.out.println(fileinputStream);System.out.println(file.getName());File[] files = file.listFiles();List<String> collect = Stream.of(files).map(f->f.getPath()).collect(Collectors.toList());System.out.println(collect);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。