时间: 2021-07-31 作者:daque
java文献操纵(3)
6.zip收缩和crc校验
杰出的发端是胜利的一半,有了上头的筹备,实行主步调也就很简单了。
public static void main(string[] args) { // 步调展示任何特殊都将打字与印刷运用消息。 try { // 记载正则表白式和路途称呼。 string regex = args[1]; string targetfolder = args[0]; file path = new file(targetfolder); arraylist files = new arraylist(); // 递归探求path所指定的文献夹内以及子文献夹内满意合正则表白式。 recursiveappend(path, files, regex); if (files.size() == 0) { system.out.println("找不就任何配合的文献!"); return; } // 把适合正则表白式的文献收缩成zip方法而且归来crc校验值。 fileoutputstream file = new fileoutputstream("backup.zip"); checkedoutputstream csum = new checkedoutputstream(file, new crc32()); zipoutputstream zos = new zipoutputstream(csum); bufferedoutputstream out = new bufferedoutputstream(zos); // 为zip包增添解释。 zos.setcomment("backup " + regex + " in " + targetfolder); // 发端收缩。 for (int i = 0; i < files.size(); i++) { string currentfile = (string) files.get(i); system.out.println("writing file " + currentfile); bufferedreader in = new bufferedreader(new filereader(currentfile)); zos.putnextentry(new zipentry(currentfile)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); } out.close(); // 当收缩包封闭此后便不妨获得crc校验值。 system.out.println("crc校验值:" + csum.getchecksum().getvalue()); } catch (exception e) { printusage(); }}
开始不妨看到,所有main因变量局部是用一个大的try...catch特殊捕捉语句包含起来的,当步调展示任何特殊时,咱们都觉得是用户的参数不精确,便挪用printusage()本领打字与印刷运用消息,简直代码从略。
开始经过recursiveappend()本领递归探求指定的文献夹内以及子文献夹内满意合正则表白式的文献名,截止将生存在files中。即使有满意前提的文献,则把那些文献收缩成zip方法,并增添符合的解释。当收缩包封闭此后便不妨获得zip包的crc校验值。
提防,之上那些代码运用的都是java api内置的功效,即使你在编写的进程中遇到找不到类设置的情景,别忘怀运用eclipse内置的ctrl+shift+m机动导出功效。至此,所有软硬件十足编写好了。你不妨在吩咐行手动输出玩弄一下,大概点击run菜单的run...菜单项,摆设eclipse运转的参数如图2所示。