Using Java to implement the operation of the folder __java

Source: Internet
Author: User
Tags stringbuffer

1, copying folders

private void CopyFile (File sourcefile,file targetfile) {try {if (!sourcefile.exists ()) {return;
					}else{if (sourcefile.isdirectory ()) {if (!targetfile.exists ()) {targetfile.mkdirs ();
					} file[] List=sourcefile.listfiles ();
						for (file f:list) {file Newfile=new file (Targetfile,f.getname ());
					CopyFile (f, newFile);
					}}else{if (!targetfile.exists ()) {targetfile.createnewfile ();
					} fileinputstream input = new FileInputStream (sourcefile); Bufferedinputstream Inbuff = new Bufferedinputstream (input);
					Creates a new file output stream and buffers it fileoutputstream output = new FileOutputStream (targetfile); Bufferedoutputstream Outbuff = new Bufferedoutputstream (output);
					Buffer array byte[] b = New byte[1024 * 5]; int Len;
					Refreshes the output stream of this buffer while (len = Inbuff.read (b))!=-1) {outbuff.write (b, 0, Len); } outbuff.flush ();
					Close flow inbuff.close ();
					Outbuff.close ();
					Output.close ();
			Input.close ();	The catch (Exception e) {tools.errorlist (E), "Copy file"); }
	}
2. Delete Folder
private void DeleteFile (file file) {
		if (file.exists ()) {if (
			file.isfile ()) {
				file.delete ();
			} else if (file.isdirectory ()) {
				file files[] = File.listfiles ();               All documents under the Declaration directory files[];
				for (int i=0;i<files.length;i++) {            //traverse directory All Files
					deletefile (files[i]);             Each file is iterated with this method
			    }
			file.delete ();
	}
3, compressed folder

File Xmfile=new file (filepath+ "FileName");
file[] filelist = Xmfile.listfiles ();
Zipoutputstream Zos = new Zipoutputstream (New FileOutputStream (filepath+ "<span style=" font-family:arial, Helvetica , Sans-serif; " >filename.</span>zip "));
if (filelist.length!=0) {for
(int i = 0; i < filelist.length i++) {
zip.zipfile (Zos, filelist[i], ""); 
  
   }
zos.close ();
  
  
    Methods in the Zip class:
<pre name= "code" class= "html" >public static void ZipFile (Zipoutputstream output, file file, String BasePath) throws
        Exception {FileInputStream FIS = null;
        Bufferedinputstream bis = null;
                try {if (File.isdirectory ()) {//file is directory file list[] = File.listfiles (); BasePath = BasePath + (basepath.length () = = 0?
                "": "/") + File.getname ();
                for (File f:list) {zipfile (output, F, basepath); } else {//compressed file BasePath = (basepath.length () = 0?
                "": BasePath + "/") + File.getname ();
                Output.putnextentry (New ZipEntry (BasePath));
                FIS = new FileInputStream (file);
                bis = new Bufferedinputstream (FIS);
                byte[] buf = new byte[1024];
                int Len;
                while (len = Bis.read (buf))!=-1) {output.write (buf, 0, Len);
             }   Output.flush ();
        The catch (Exception ex) {throw ex;
            finally {if (bis!= null) {bis.close ();
            } if (FIS!= null) {fis.close (); }
        }
    }


<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); >4, unzip zip file </span>

public static void Upzip (File unzipfile,file unzipfolder) throws exception{InputStream input = null;  
		  OutputStream output = null;
		  ZipFile zipfile = null;  try {zipfile = new ZipFile (unzipfile);  Create a ZIP file Object enumeration Zipenum = Zipfile.getentries ();  Gets the ZIP file entry Enumeration Object ZipEntry entry = null;  
				Define object String EntryName = null, PATH = NULL;  
				String names[] = null;  
				int length;  while (Zipenum.hasmoreelements ()) {//circular read Entry entry = (ZipEntry) zipenum.nextelement ();  
				    Gets the current entry EntryName = new String (Entry.getname ());  
				    names = Entryname.split ("\\/") with/delimited entry name;  
				    length = Names.length;
				    Path = Unzipfolder.getabsolutepath (); for (int v = 0; v < length; v++) {if (v < length-1) {//directory file Tempfile=new file before the last directory (
				    		Path + = "/" + Names[v] + "/");
				    		if (!tempfile.exists ()) {tempfile.mkdirs (); }}else {//Last 
				    		if (Entryname.endswith ("/")) {//is a directory, create the folder file Tempfile=new file (Unzipfolder.getabsolutepath () +
					    		"/" + EntryName);
					    		if (!tempfile.exists ()) {tempfile.mkdirs ();  
				    			}else {//is a file, output to file input = Zipfile.getinputstream (entry);  
				    			Output = new FileOutputStream (New File (Unzipfolder.getabsolutepath () + "/" + EntryName));  
				    			byte[] buffer = new byte[1024 * 8];  
				    			int readlen = 0;  
				    			while ((Readlen = input.read (buffer, 0, 1024 * 8))!=-1) {output.write (buffer, 0, Readlen);  
				    			} if (input!= null) input.close ();  
				    				if (output!= null) {Output.flush ();  
				    			Output.close ();
		  catch (Exception ex) {throw ex;  
				   Finally {try {if (input!= null) input.close ();  
				  if (output!= null) {  Output.flush ();  
				   Output.close (); 
				   } if (Zipfile!=null) {zipfile.close (); The catch (Exception e) {}}}
5, write the file into a binary stream string

public static String ziptostr (file file) throws exception{
		 stringbuffer suf = new StringBuffer ();
		 FileInputStream FIS = null;
                 int temp = 0;
                 FIS = new FileInputStream (file);
                 while (temp = Fis.read ())!=-1) {
        	<span style= "White-space:pre" >	</span>suf.append (temp);
        	<span style= "White-space:pre" >	</span>suf.append (",");
        <span style= "White-space:pre" >	</span>}
         <span style= "White-space:pre" >	</ Span>fis.close ();
		return suf.tostring ();
	 }
6. Convert binary stream to file

public static file Strtozip (String str,file file) throws exception{
		 fileoutputstream fos = new FileOutputStream (file) ;
		 string[] Str_arr = Str.split (",");
		 for (String V:str_arr) {
			fos.write (integer.valueof (v));
		 }
		 Fos.close ();
		 return file;
	 }






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.