The requirement is that there is a ZIP package on the server that operates the upload, the content is the user's photo, what I need to do is get these photos uploaded and saved to the database. This upload photos, save the database is not difficult, the main problem is to unzip the zip package, and delete the zip package, as well as the extracted files.
Before the network to find the extracted files of the code, there is the same problem, that is, after decompression, can not delete the zip package. Baidu said it is resource use, but I have put all the flow is closed wow.
I split the decompression and deletion into two parts with JUnit test: The first Test decompression, does not delete the package, the second time only delete the package. I found that the decompression method and the deletion method in the same test, the ZIP package can not be deleted, if a separate test to delete the method, the zip package is deleted. Summarize that the package cannot be deleted after extracting it in the same thread. This must be a resource in use.
I added a garbage collection in the Code (System.GC ();), still not ...
I still do not give up, or to find the code on Baidu, see if others have encountered such problems, I saw a lot of, also tested a lot of code, found that many of the blog is copied, perhaps other people read this blog solved the problem, and then do not want to summarize, so, the blog to their own blog, This is easy, but after all, not their own original, I am a support for the original person. (although I may have copied it too, but I did not publish Wow). It's still not good to see so much. Suddenly my buckle lit a bit, the boss sent a picture.
Sure enough, plus to go after the e-disk file really disappeared.
The problem that bothered me this morning was solved, and it was my sentence, "the more difficult it seems, the more simple the problem is." Strange question ", just a concept, just exist in my heart, so this sentence can only be me and myself said.
No, look at the code. A total of two classes Phototaskservice.java and Ziputil.java
Package Com.hupu.smart.user.service.phototask;import Com.hupu.smart.user.domain.userphoto;import Com.hupu.smart.user.interfaces.userphotoservice;import Com.hupu.smart.user.service.util.uploadimageutil;import Com.hupu.smart.user.service.util.ziputil;import Org.slf4j.logger;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.beans.factory.annotation.value;import org.springframework.scheduling.annotation.Scheduled; Import Org.springframework.stereotype.service;import java.io.*;import Java.util.arraylist;import java.util.List;/* * * Created by Wangjunnan on 2017/4/1. */@Service ("Phototaskservice") public class Phototaskservice {@Value ("#{configproperties[' Oss_endpoint_url '}") pri Vate String ENDPOINT; @Value ("#{configproperties[' oss_access_id '}") private String access_id; @Value ("#{configproperties[' Oss_access_key '}") private String Access_key; @Value ("#{configproperties[' Oss_domain '}") private String Oss_domain; @ValuE ("#{configproperties[' Oss_bucket '}") private String bucket; @Autowired private Userphotoservice Photoservice; Private Logger log = Org.slf4j.LoggerFactory.getLogger (Phototaskservice.class); Private String url= "E:\\image"; Check for files that are not present in zip and return these files @Scheduled (cron= "0/10 * * * *? ") public void Searchzipfile () {log.info (" Unzip user photo task start execution "); list<file> list= new arraylist<> (); File file=new file (URL); if (File.isdirectory ()) {file[] files = file.listfiles (); for (File f:files) {if (F.getname (). EndsWith (". zip")) {//zip file to determine if there is List.add (f) ; }}} if (null!=list && list.size () >0) {//If there is a file, unzip and save the Releasezipfile (list ); } log.info ("Unzip user photo task completed"); Delete the extracted files Deletedir (new file (URL)); }//Unzip the zip file to return list<userphoto> public void Releasezipfile (List<file> files) {list<userphoto> photos=new arraylist<> (); try{for (File f:files) {list<file> fileList = Ziputil.upzipfile (f, URL); Delzipfile (); Delete the zip package for (int i=0;i<filelist.size (); i++) {String userid=filelist.get (i) after decompression is complete. Getpare Ntfile (). GetName (); Upload String Photourl = uploadimageutil.uploadpic (Filelist.get (i), "photo", ENDPOINT, access_id, Access_key , BUCKET, Oss_domain); Log.info ("User image upload Success"); Encapsulated into User_photo object Userphoto photo=new Userphoto (); Photo.setuserid (USERID); Photo.setphotopath (Photourl); Photo.setstate (0); Photo.setisdel (0); Photos.add (photo); }}//Save to Database Photoservice.adduserphoto (PHOTOS); Log.info ("Data saved to database"); }catch (Exception e) {log.error ("error on Photo" +e.getmessage ()); }}//delete zip file public void Delzipfile () {file file=new file (URL); if (File.isdirectory ()) {file[] files = file.listfiles (); The for (File f:files) {if (F.getname (). EndsWith (". zip")) {//zip file Determines if there is an if (F.delete ( ) {log.info ("Zip file has been deleted"); }else{log.info ("Zip file deletion failed"); }}}}}//delete the extracted file private boolean deletedir (file dir) {if (Dir.isdirec Tory ()) {string[] children = dir.list (); Recursively delete subdirectories in directory for (int i=0; i<children.length; i++) {Boolean success = Deletedir (New File (dir, chil Dren[i])); if (!success) {return false; }}}//directory is empty at this time, you can delete return Dir.delete (); }}
Ziputil.java
Package Com.hupu.smart.user.service.util;import Java.io.file;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.util.ArrayList;import Java.util.enumeration;import Java.util.list;import Org.apache.tools.zip.zipentry;import Org.apache.tools.zip.zipfile;import org.slf4j.logger;/** * Compress or unzip zip: * Due to the use of classes under the Java.util.zip Toolkit, there is a problem with Chinese garbled, so use the tool class under Org.apache.tools.zip in Ant.jar * @author Administrator */public class Ziputil {private static byte[] _byte = new byte[1024]; private static Logger log = Org.slf4j.LoggerFactory.getLogger (Ziputil.class); /** * Unzip the. zip file * @param zipfile unzip the file * @param descdir compressed target address, such as: d:\\ test or/mnt/d/Test * @return */ public static list<file> Upzipfile (File zipfile, String descdir) {list<file> _list = new ArrayList <> (); try {zipfile _zipfile = new ZipFile (ZipFile, "GBK"); For (Enumeration entries = _zipfIle.getentries (); Entries.hasmoreelements (); ) {ZipEntry entry = (zipentry) entries.nextelement (); File _file = new file (Descdir + file.separator + entry.getname ()); if (Entry.isdirectory ()) {_file.mkdirs (); }else{File _parent = _file.getparentfile (); if (!_parent.exists ()) {_parent.mkdirs (); } InputStream _in = _zipfile.getinputstream (entry); OutputStream _out = new FileOutputStream (_file); int Len; while (len = _in.read (_byte)) > 0) {_out.write (_byte, 0, Len); } if (null!=_out) {_out.flush (); _out.close (); } if (null!=_in) {_in.close (); } _list.add (_file); } }
After adding this line of code, you can delete_zipfile.close ();//Add this line of code and you can delete theAfter adding this line of code, you can delete
} catch (IOException e) {log.error (E.getmessage ()); } return _list; }}
And then you can test it with JUnit.
@Testpublic void Testphoto () { taskservice.searchzipfile ();}
Java unzip the zip package and delete