java解压缩

package c4_test;

import javax.crypto.;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.
;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Enumeration;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class C4_java {
public static void main(String[] args) throws NoSuchPaddingException, IllegalBlockSizeException, IOException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
String url = “https://csdn-task.oss-cn-hangzhou.aliyuncs.com/demo/studyNginx.zip”;
//完成目标文件的下载和解压
DownAndReadFile(url);
//过滤出目标文件夹下的所有文件进行AES加密
File file = new File(“C:\Users\Administrator\Desktop\exam\studyNginx”);
File[] files = file.listFiles();
AESEncrpt(new File(“C:\Users\Administrator\Desktop\exam\studyNginx\001.txt”));
//for(File f : files){
// if(f.isFile()){
// AESEncrpt(f);
// }
// }
}

//下载并读取文件
public static void DownAndReadFile(String filePath){
    //要下载到的本地的文件夹
    String dir = "C:\\Users\\Administrator\\Desktop\\exam";
    File saverPath = new File(dir);
    if(!saverPath.exists()){
        saverPath.mkdir();
    }
    //根据/切割接收到的请求网络的url
    String[] urlName = filePath.split("/");
    //获取到切割字符串数据长度-1
    int len = urlName.length-1;
    //获取到请求下载的文件的名称
    String uname = urlName[len];
    System.out.println(uname);//studyNginx.zip

    try{
        //创建保存的新文件
        File file = new File(saverPath+"//"+uname);
        if(file != null || !file.exists()){
            file.createNewFile();
        }
        //通过高效字节输出流输出创建的文件对象
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
        URL url = new URL(filePath);
        //返回一个URLConnection实例,表示与URL应用的远程对象
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoInput(true);
        uc.connect();//打开与此URL引用的通信链接
        //获取服务端的字节输入流
        InputStream inputStream = uc.getInputStream();
        System.out.println("file size is:"+uc.getContentLength());
        //声明字节数组来存放读取的文件
        byte[] b = new byte[1024*4];
        int byteRead = -1;//定义读取次数
        while((byteRead = inputStream.read(b))!=-1){
            bufferedOutputStream.write(b,0,byteRead);
        }
        //关闭流和刷新流
        inputStream.close();
        bufferedOutputStream.close();
        System.out.println("文件下载成功!");

        //————————解压文件————————
        StringBuffer strb = new StringBuffer();
        //创建高效的字节输入管道
        BufferedInputStream fs = new BufferedInputStream(new FileInputStream(saverPath + "//" + uname));
        BufferedReader br = new BufferedReader(new InputStreamReader(fs, "UTF-8")); // 指定读取的编码格式); // 高效缓存字节读取
        String date = ""; // 记录读取一行的数据
        //循环读取
        while((date = br.readLine())!=null){
            strb.append(date+"\n");
        }
        br.close();
        fs.close();
        System.out.println("解压文件中。。。");
        //解压
        unZipFiles(dir+"/studyNginx.zip",dir+"/");
    }catch(Exception e){
        e.printStackTrace();
    }
}

public static void unZipFiles(String zipPath, String descDir) throws Exception {
    System.out.println("解压文件的名称:" + zipPath + "\n解压的文件存放路径:" + descDir);
    unZipFiles(new File(zipPath), descDir); // 调用方法
    //File zipFile
}

//解压文件
public static void unZipFiles(File zipFile, String descDir) throws IOException {

    ZipFile zip = new ZipFile(zipFile,Charset.forName("GBK"));//解决中文文件夹乱码
    String name = zip.getName().substring(zip.getName().lastIndexOf('\\')+1, zip.getName().lastIndexOf('.'));

    File pathFile = new File(descDir+name);
    if (!pathFile.exists()) {
        pathFile.mkdirs();
    }

    for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        String zipEntryName = entry.getName();
        InputStream in = zip.getInputStream(entry);
        String outPath = (descDir + name +"/"+ zipEntryName).replaceAll("\\*", "/");

        // 判断路径是否存在,不存在则创建文件路径
        File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
        if (!file.exists()) {
            file.mkdirs();
        }
        // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
        if (new File(outPath).isDirectory()) {
            continue;
        }
        // 输出文件路径信息
        System.out.println(outPath);

        FileOutputStream out = new FileOutputStream(outPath);
        byte[] buf1 = new byte[1024];
        int len;
        while ((len = in.read(buf1)) > 0) {
            out.write(buf1, 0, len);
        }
        in.close();
        out.close();
    }
    System.out.println("******************解压完毕********************");
    return;
}


static final String ALGORITHM ="AES";
public static SecretKey generateKey() throws NoSuchAlgorithmException {
    KeyGenerator secretGenerator = KeyGenerator.getInstance(ALGORITHM);
    SecureRandom secureRandom = new SecureRandom();
    secretGenerator.init(secureRandom);
    SecretKey secretKey = secretGenerator.generateKey();
    return secretKey;
}

private static byte[] aes(byte[] contentArray , int mode , SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(mode,secretKey);
    byte[] result = cipher.doFinal(contentArray);
    return result;
}

static Charset charset = Charset.forName("UTF-8");
public static byte[] encrypt(String content, SecretKey secretKey) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
    return aes(content.getBytes(charset),Cipher.ENCRYPT_MODE,secretKey);
}

//AES加密

public static void AESEncrpt(File file) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException {
try {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(new File(“C:\Users\Administrator\Desktop\exam\studyNginx\a.txt”));

       //秘钥自动生成
       KeyGenerator keyGenerator=KeyGenerator.getInstance("AES");
       keyGenerator.init(128);
       Key key=keyGenerator.generateKey();


       byte[] keyValue=key.getEncoded();

       fos.write(keyValue);//记录输入的加密密码的消息摘要

       SecretKeySpec encryKey= new SecretKeySpec(keyValue,"AES");//加密秘钥

       byte[] ivValue=new byte[16];
       Random random = new Random(System.currentTimeMillis());
       random.nextBytes(ivValue);
       IvParameterSpec iv = new IvParameterSpec(ivValue);//获取系统时间作为IV

       fos.write("MyFileEncryptor".getBytes());//文件标识符

       fos.write(ivValue);	//记录IV
       Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
       cipher.init(cipher.ENCRYPT_MODE, encryKey,iv);

       CipherInputStream cis=new CipherInputStream(fis, cipher);

       byte[] buffer=new byte[1024];
       int n=0;
       while((n=cis.read(buffer))!=-1){
           fos.write(buffer,0,n);
       }
       cis.close();
       fos.close();
       fis.close();

       fos = new FileOutputStream(file);
       fis = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\exam\\studyNginx\\a.txt"));
       byte[] bytes = new byte[1024];
       int len = 0;
       while((len = fis.read(bytes,0,len))!=-1){
           fos.write(bytes,0,len);
       }
       fis.close();
       fos.close();
   } catch (InvalidKeyException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
   } catch (FileNotFoundException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
   } catch (NoSuchPaddingException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
   } catch (InvalidAlgorithmParameterException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
   } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
   }

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值