目录
- Java利用NIO压缩文件或文件夹
- java.io包和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.Zip编程Entry;
import java.util.zip.ZipOutputStream;
public class CompressUtils {
private static ZipOutputStream zipOutputStream=null;
private static ByteBuffer byteBuffer = ByteBphpuffer.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||androidfiles.length==0){
try {
zipOutputStream.putNextEntry(new ZipEntry(file.getAbsolutePath().substring(3,file.getAbsolutePath().length())+"/"));
zipOutputStream.closeEntry();
} cjavascriptatch (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)。
面向流意味着一次读取一个或者一些字节,然后处理这些字节,在读取和处理这些字节时当前线程是阻塞的,不能干其他事情。
面向缓存意味着把一些字节读到缓存里面,选择了读取的字节之后当前线程可以去做其他事情,以后再去处理缓存里面的字节也可以,也就是线程非阻塞。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
加载中,请稍侯......
精彩评论