Java File copy function

Source: Internet
Author: User

In writing code, it is often necessary to copy files. These functions can then be put into the tool class.

Here is a function to copy the file:

public class Copyfileutil {private static String MESSAGE = "";            /** * Copy a single file * * @param srcfilename * file name to be copied * @param descfilename * Target filename * @param overlay * If the destination file exists, overwrite * @return If the copy succeeds returns TRUE, otherwise false */public STA Tic Boolean CopyFile (String srcfilename, String destFileName, Boolean overlay) {File srcfile = new            File (Srcfilename); Determine if the source file exists if (!srcfile.exists ()) {MESSAGE = "source file:" + Srcfilename + "does not exist!              ";              Joptionpane.showmessagedialog (null, MESSAGE);          return false; } else if (!srcfile.isfile ()) {MESSAGE = "Copy file failed, source file:" + Srcfilename + "is not a file!              ";              Joptionpane.showmessagedialog (null, MESSAGE);          return false;          }//To determine if the target file exists with the files DestFile = new file (destfilename); if (destfile.exists ()) {//If the destination file exists and allows overwriting              if (overlay) {//delete the target file that already exists, regardless of whether the destination file is a directory or a single file (destFileName). delet              E ();                  }} else {//If the destination file is located in a directory that does not exist, create a directory if (!destfile.getparentfile (). exists ()) { The directory where the destination file is located does not exist if (!destfile.getparentfile (). Mkdirs ()) {//Copy file failed: The directory where the target file was created is missing                  Fail to return false; }}}//copy file int byteread = 0;          Number of bytes read InputStream in = null;            OutputStream out = null;              try {in = new FileInputStream (srcfile);              out = new FileOutputStream (destfile);                byte[] buffer = new byte[1024];              while ((Byteread = in.read (buffer))! =-1) {out.write (buffer, 0, byteread);          } return true;          } catch (FileNotFoundException e) {return false; } catch (IOException E) {return false;                  } finally {try {if (out! = null) out.close ();              if (in = null) In.close ();              } catch (IOException e) {e.printstacktrace ();   }          }      }

  

How to copy an entire folder:

 /** * Copy the contents of the entire directory * * @param srcdirname * Directory name of the directory to be copied * @param destdirname *  Target directory name * @param overlay * If the destination directory exists, overwrite * @return If the copy succeeds returns TRUE, otherwise false */public           Static Boolean CopyDirectory (String srcdirname, String destdirname, Boolean overlay) {//To determine if the source directory exists          File Srcdir = new file (srcdirname); if (!srcdir.exists ()) {MESSAGE = "Copy directory failed: Source directory" + Srcdirname + "does not exist!              ";              Joptionpane.showmessagedialog (null, MESSAGE);          return false; The Else if (!srcdir.isdirectory ()) {MESSAGE = "copy directory failed:" + Srcdirname + "is not a directory!              ";              Joptionpane.showmessagedialog (null, MESSAGE);          return false; }//If the target directory name does not end with a file delimiter, add the file delimiter if (!destdirname.endswith (File.separator)) {destDirName          = destDirName + file.separator;  } File DestDir = new file (destdirname);        If the destination folder exists if (Destdir.exists ()) {//If overwrite is allowed delete the existing target directory if (overlay) {              New File (destdirname). Delete (); } else {MESSAGE = "failed to replicate directory: Destination directory" + destDirName + "already exists!                  ";                  Joptionpane.showmessagedialog (null, MESSAGE);              return false; }} else {//Create destination directory System.out.println ("Destination directory does not exist, prepare to create ...              "); if (!destdir.mkdirs ()) {System.out.println ("failed to replicate directory: Failed to create destination directory!")                  ");              return false;          }} Boolean flag = true;          file[] files = srcdir.listfiles (); for (int i = 0; i < files.length; i++) {//Copy file if (Files[i].isfile ()) {FL AG = Copyfileutil.copyfile (Files[i].getabsolutepath (), destDirName + files[i].getname (), overlay)                  ;        if (!flag) break;      } else if (Files[i].isdirectory ()) {flag = Copyfileutil.copydirectory (), Files[i].getabsolutepath (),                  destDirName + files[i].getname (), overlay);              if (!flag) break; }} if (!flag) {MESSAGE = "copy directory" + Srcdirname + "to" + destDirName + "failed!              ";              Joptionpane.showmessagedialog (null, MESSAGE);          return false;          } else {return true;          }} public static void Main (string[] args) {String srcdirname = "C:/test/test0/test1";          String destdirname = "C:/TTT";      Copyfileutil.copydirectory (Srcdirname, destDirName, true);  }  }

  

Java File copy function

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.