Java copies files or entire folders from one directory to another

Source: Internet
Author: User

* * Copy a single file * @param oldpath string original file path such as: C:/fqf.txt * @param newpath string after copy path such as: F:/fqf.txt * @return Boolean */Pub LIC void CopyFile (String oldpath, String NewPath) {try {int bytesum = 0; int byteread = 0; File Oldfile = new file (OldPath); if (oldfile.exists ()) {//file exists InputStream instream = new FileInputStream (oldpath);//Read in original file FileOutputStream fs = new Fil Eoutputstream (NewPath); byte[] buffer = new byte[1444]; int length; while ((Byteread = instream.read (buffer))! =-1) {bytesum + = byteread;//bytes File size System.out.println (bytesum); Fs.write ( Buffer, 0, byteread); } instream.close (); }} catch (Exception e) {System.out.println ("error copying Single file operation"); E.printstacktrace ();}} /** * Copy entire folder Contents * @param oldpath String original file path such as: C:/FQF * @param newpath string after copy path such as: F:/FQF/FF * @return Boolean */Publ IC void CopyFolder (String oldpath, String NewPath) {try {(new File (NewPath)).//If the folder does not exist, create a new folder file Mkdirs a=new E (OldPath); String[] File=a.list (); File Temp=null; for (int i = 0;i < file.length; i++) {if (Oldpath.endswith (File.separator)) {temp=new file (Oldpath+file[i]);} else{temp=new file (oldpath+ File.separator+file[i]); } if (Temp.isfile ()) {FileInputStream input = new FileInputStream (temp); FileOutputStream output = new FileOutputStream (NewPath + "/" + (Temp.getname ()). ToString ()); Byte[] B = New byte[1024 * 5]; int Len; while (len = Input.read (b))! =-1) {output.write (b, 0, Len);} output.flush (); Output.close (); Input.close (); } if (Temp.isdirectory ()) {//If it is a subfolder copyfolder (oldpath+ "/" +file[i],newpath+ "/" +file[i]);}} } catch (Exception e) {System.out.println ("error copying entire folder contents operation"); E.printstacktrace ();}}

Java copies files or entire folders from one directory to another directory

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.