java如何利用NIO压缩文件或文件夹
java利用NIO压缩文件或文件夹
package liu.cn.ixj.util; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class CompressUtils { private static ZipOutputStream zipOutputStream=null; private static ByteBuffer byteBuffer = ByteBuffer.allocate(1024); public static void main(String[] args) { try { zipOutputStream=new ZipOutputStream(new FileOutputStream(new File("E://aa.zip"))); toZip(new File("E:\\MyDownloads")); zipOutputStream.flush(); zipOutputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void toZip(File file){ if (file.isFile()){ try { zipOutputStream.putNextEntry(new ZipEntry(file.getAbsolutePath().substring(3,file.getAbsolutePath().length()))); FileChannel channel = new FileInputStream(file).getChannel(); while (true){ byteBuffer.clear(); int read = channel.read(byteBuffer); if (read==-1)break;; zipOutputStream.write(byteBuffer.array()); } channel.close(); zipOutputStream.closeEntry(); } catch (IOException e) { e.printStackTrace(); } }else { File[] files = file.listFiles(); if (files==null||files.length==0){ try { zipOutputStream.putNextEntry(new ZipEntry(file.getAbsolutePath().substring(3,file.getAbsolutePath().length())+"/")); zipOutputStream.closeEntry(); } catch (IOException e) { e.printStackTrace(); } }else { for (File file2:files) { toZip(file2); } } } } }
java.io包和java.nio包
Java中I/O相关的两个包是java.io和java.nio,它们的最重要的区别就是java.io里面的类是面向流的(stream oriented),java.nio里面的类是面向缓存的(buffer oriented)。
面向流意味着一次读取一个或者一些字节,然后处理这些字节,在读取和处理这些字节时当前线程是阻塞的,不能干其他事情。
面向缓存意味着把一些字节读到缓存里面,选择了读取的字节之后当前线程可以去做其他事情,以后再去处理缓存里面的字节也可以,也就是线程非阻塞。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Caused by: java.lang.NumberFormatException: For input s
这篇文章主要介绍了Caused by: java.lang.NumberFormatException: For input string: “port“,本文给大家分享完美解决方法,需要的朋友可以参考下2023-01-01Java中StringUtils与CollectionUtils和ObjectUtil概念讲解
这篇文章主要介绍了Java中StringUtils与CollectionUtils和ObjectUtil概念,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧2022-12-12SpringBoot解决BigDecimal传到前端后精度丢失问题
这篇文章将通过示例详细为大家介绍SpringBoot如何解决BigDecimal传到前端后精度丢失问题,文中的示例代码讲解详细,感兴趣的可以了解一下2022-06-06
最新评论