我正在参加「掘金·启航计划」
前言
距离上一篇沾点儿技术的文章已经过去五十多天了,这期间本小前端一点儿页面也没碰。。。反倒去写了几个后端的接口,和一个小的java项目,离了个大谱了吧!赶上现在有点儿心思就总结一下最近学到的东西吧!今天先写文件解压相关~(刚刚得知附近又有疫情了,求求了,让我十一能回家,不然这个世界上又会多一个伤心的人!!!!!!)
待解压文件层级
如上图,简化拆分一下需求即:根据文件路径,解压其中的.gz文件,得到如下图所示的file;
根据文件路径解压.zip
/**
* zip解压
* @param inputFile 待解压文件路径
* @param destDirPath 解压得到的文件路径
*/
public static void zipUncompress(String inputFile, String destDirPath) throws Exception {
long start = System.currentTimeMillis();
File srcFile = new File(inputFile);//获取当前压缩文件
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new Exception(srcFile.getPath() + "所指文件不存在");
}
//开始解压
//构建解压输入流
ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile));
ZipEntry entry = null;
File file = null;
while ((entry = zIn.getNextEntry()) != null) {
if (!entry.isDirectory()) {
file = new File(destDirPath, entry.getName());
if (!file.exists()) {
new File(file.getParent()).mkdirs();//创建此文件的上级目录
}
OutputStream out = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(out);
int len = -1;
byte[] buf = new byte[1024];
while ((len = zIn.read(buf)) != -1) {
bos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
bos.close();
out.close();
}
}
long end = System.currentTimeMillis();
LOG.info("解压zip完成,耗时:" + (end - start) + " ms");
}
执行完解压.zip的代码后,在存放解压后内容的路径下得到的内容如下:
根据文件路径解压.gz文件
/**
* gz解压
* @param sourcedir 待解压文件名
*/
public static String unGzipFile(String sourcedir) {
long start = System.currentTimeMillis();
String ouputfile = "";
try {
//建立gzip压缩文件输入流
String gzPath = sourcedir.replace(".zip\","\");
LOG.info("gzPath: " + gzPath);
FileInputStream fin = new FileInputStream(gzPath);
//建立gzip解压工作流
GZIPInputStream gzin = new GZIPInputStream(fin);
//建立解压文件输出流
ouputfile = gzPath.substring(0,gzPath.lastIndexOf('.'));
System.out.println("outputfile " + ouputfile);
FileOutputStream fout = new FileOutputStream(ouputfile);
int num;
byte[] buf=new byte[1024];
while ((num = gzin.read(buf,0,buf.length)) != -1)
{
fout.write(buf,0,num);
}
long end = System.currentTimeMillis();
LOG.info("解压gz文件完成,耗时:" + (end - start) + " ms");
gzin.close();
fout.close();
fin.close();
} catch (Exception ex){
System.err.println(ex.toString());
}
return ouputfile;
}
因为整个流程是解压zip,然后在解压后的文件路径下再解压其中的gz文件,所以上述代码中有一些关于路径的处理;解压完成后,得到的内容如下:
总结
作为一个面向百度开发的前端,写后端代码可想而知了哈哈哈哈;以上只是第一版,后来都没用;今天再一看其中的代码确实好乱呀(这里的两个方法是能用的哦),果然写代码需要很好的逻辑性才行!老板评审这一版代码时直呼我是个人才
说正经的,越来越发现自己没有接触过的东西太多,而且每次遇到了新的东西也只是草草的拿来主义,能用就行,都没有深究过。等闲下来想研究一下又发现真的超级晦涩难懂,各位大佬们当初入行的时候有这样的阶段吗?大家又是怎么突破的呢?