Java implementation file copy upload Operation _java

Source: Internet
Author: User
Tags file copy file separator

Use Java to copy files everywhere can be used, here summed up a class for everyone to reference. There are a total of two methods:

public static Boolean CopyFile (String srcfilename, String Destfilename,boolean overlay); 
public static Boolean CopyDirectory (String srcdirname, String Destdirname,boolean overlay); 

which
srcfilename file names to be copied
descfilename target file name
Overlay If the target file exists, overwrite
Returns False if the copy succeeds returning True

Code:

 Import Java.io.File; 
Import Java.io.FileInputStream; 
Import java.io.FileNotFoundException; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
 
Import Java.io.OutputStream; 
 
Import Javax.swing.JOptionPane; 
 
  /** * Copy files or Folders * * ZWW/public class Copyfileutil {private static String message = "";  /** * Copy Single file * * @param srcfilename * file name to be copied * @param descfilename * Target filename * @param Overlay * If the target file exists, overwrite * @return If the copy succeeds returning true, return false */public static Boolean CopyFile (String src 
 
    FileName, 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; 
    //Determine if the target file exists with the filename destfile = new file (destfilename); if (destfile.exists ()) {//If the target file exists and allows overwrite if (overlay) {///delete existing target file, whether the target file is a directory or a single file NE 
      W File (destfilename). Delete (); 
        } else {//if the directory in which the destination file is located does not exist, create the directory if (!destfile.getparentfile (). exists ()) {//destination file directory does not exist 
        if (!destfile.getparentfile (). Mkdirs ()) {///Copy file failed: The directory where the target file was created failed 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 (IOExceptionE) {return false; 
        Finally {try {if (out!= null) out.close (); 
      if (in!= null) in.close (); 
      catch (IOException e) {e.printstacktrace ();      /** * Copy the contents of the entire directory * * @param srcdirname * Directory name of the directory to be replicated * @param destdirname * Target directory name * @param overlay * If the target directory exists, overwrite * @return If the replication returns true successfully, return false/public static Boole  An copydirectory (string srcdirname, String destdirname, Boolean overlay) {//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; else if (!srcdir.isdirectory ()) {message = Copy directory failed: + Srcdirname + is not a directory! 
      "; 
      Joptionpane.showmessagedialog (null, message); 
    return false; ///If the destination directory name does not end with a file delimiter, the file separator 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 = ' Replicate directory failed: Destination directory + destDirName + ' already exists! 
        "; 
        Joptionpane.showmessagedialog (null, message); 
      return false; } else {//Create destination directory System.out.println ("Destination directory does not exist, ready to create ...") 
      "); if (!destdir.mkdirs ()) {System.out.println ("Replication directory failed: Create destination directory failed!") 
        "); 
      return false; 
    } Boolean flag = true; 
    file[] files = srcdir.listfiles (); for (int i = 0; i < files.length i++) {//Copy file if (Files[i].isfile ()) {flag = copyfileutil.co 
        Pyfile (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); 
 } 
}

Regardless of multithreading optimization, single-threaded file replication is the fastest way (the larger the file the more advantages of the method, generally faster than the usual method 30+%):

private static void Niotransfercopy (file source, file target) { 
  filechannel in = null; 
  FileChannel out = null; 
  FileInputStream instream = null; 
  FileOutputStream outstream = null; 
  try { 
    instream = new FileInputStream (source); 
    OutStream = new FileOutputStream (target); 
    in = Instream.getchannel (); 
    out = Outstream.getchannel (); 
    In.transferto (0, In.size (), out); 
  catch (IOException e) { 
    e.printstacktrace (); 
  } finally {close 
    (instream); 
    Close (in); 
    Close (OutStream); 
    Close (out); 
  } 
 

If you need to monitor replication progress, you can use the second fastest method (note the size of the buffer, the speed has a significant impact):

private static void Niobuffercopy (file source, file target) { 
  filechannel in = null; 
  FileChannel out = null; 
  FileInputStream instream = null; 
  FileOutputStream outstream = null; 
  try { 
    instream = new FileInputStream (source); 
    OutStream = new FileOutputStream (target); 
    in = Instream.getchannel (); 
    out = Outstream.getchannel (); 
    Bytebuffer buffer = bytebuffer.allocate (4096); 
    while (in.read (buffer)!=-1) { 
      buffer.flip (); 
      Out.write (buffer); 
      Buffer.clear (); 
    } 
  catch (IOException e) { 
    e.printstacktrace (); 
  } finally {close 
    (instream); 
    Close (in); 
    Close (OutStream); 
    Close (out); 
  } 
 

the commonly used Method 1 is:

private static void Custombufferbufferedstreamcopy (file source, file target) { 
  InputStream FIS = null; 
  OutputStream fos = null; 
  try { 
    fis = new Bufferedinputstream (new FileInputStream (source)); 
    FOS = new Bufferedoutputstream (new FileOutputStream (target)); 
    byte[] buf = new byte[4096]; 
    int i; 
    while ((i = Fis.read (BUF))!=-1) { 
      fos.write (buf, 0, I); 
    } 
  } 
  catch (Exception e) { 
    e.printstacktrace (); 
  } finally {close 
    (FIS); 
    Close (FOS); 
  } 
} 

the commonly used Method 2 is:

private static void Custombufferstreamcopy (file source, file target) { 
  InputStream FIS = null; 
  OutputStream fos = null; 
  try { 
    fis = new FileInputStream (source); 
    FOS = new FileOutputStream (target); 
    byte[] buf = new byte[4096]; 
    int i; 
    while ((i = Fis.read (BUF))!=-1) { 
      fos.write (buf, 0, I); 
    } 
  } 
  catch (Exception e) { 
    e.printstacktrace (); 
  } finally {close 
    (FIS); 
    Close (FOS); 
  } 
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.