这几种错一般都是未关闭或者流的关闭顺序不对,可以使用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);}