java implements file copy and upload operation

  • 2020-05-19 04:47:20
  • OfStack

Copying files with Java can be used everywhere, and here is a summary of a class for your reference. There are two methods:


public static boolean copyFile(String srcFileName, String destFileName,boolean overlay); 
public static boolean copyDirectory(String srcDirName, String destDirName,boolean overlay) ; 

Among them:
srcFileName file name to be copied
descFileName target file name
overlay whether to overwrite if the destination file exists
Returns true if the copy succeeds, false if not

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 a single file  
   * 
   * @param srcFileName 
   *       The file name to be copied  
   * @param descFileName 
   *       Target file name  
   * @param overlay 
   *       If the target file exists, whether to overwrite it  
   * @return  Returns if the copy succeeds true Otherwise return false 
   */ 
  public static boolean copyFile(String srcFileName, String destFileName, 
      boolean overlay) { 
    File srcFile = new File(srcFileName); 
 
    //  Determine if the source file exists  
    if (!srcFile.exists()) { 
      MESSAGE = " The source file: " + srcFileName + " Does not exist! "; 
      JOptionPane.showMessageDialog(null, MESSAGE); 
      return false; 
    } else if (!srcFile.isFile()) { 
      MESSAGE = " Copy file failed, source file: " + srcFileName + " not 1 A file! "; 
      JOptionPane.showMessageDialog(null, MESSAGE); 
      return false; 
    } 
 
    //  Determine if the target file exists  
    File destFile = new File(destFileName); 
    if (destFile.exists()) { 
      //  If the target file exists and allows overwriting  
      if (overlay) { 
        //  Deletes existing target files, whether the target file is a directory or a single file  
        new File(destFileName).delete(); 
      } 
    } else { 
      //  If the directory where the target file resides does not exist, the directory is created  
      if (!destFile.getParentFile().exists()) { 
        //  The directory where the target file resides does not exist  
        if (!destFile.getParentFile().mkdirs()) { 
          //  Copy file failed: the directory where the target file was created failed  
          return false; 
        } 
      } 
    } 
 
    //  Copy the 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(); 
      } 
    } 
  } 
 
  /** 
   *  Copy the contents of the entire directory  
   * 
   * @param srcDirName 
   *       The directory name of the directory to be copied  
   * @param destDirName 
   *       Target directory name  
   * @param overlay 
   *       If the target directory exists, whether to overwrite it  
   * @return  Returns if the copy succeeds true Otherwise return false 
   */ 
  public static boolean copyDirectory(String srcDirName, String destDirName, 
      boolean overlay) { 
    //  Determine if the source directory exists  
    File srcDir = new File(srcDirName); 
    if (!srcDir.exists()) { 
      MESSAGE = " Failed to copy directory: source directory " + srcDirName + " Does not exist! "; 
      JOptionPane.showMessageDialog(null, MESSAGE); 
      return false; 
    } else if (!srcDir.isDirectory()) { 
      MESSAGE = " Copy directory failed: " + srcDirName + " Not a directory! "; 
      JOptionPane.showMessageDialog(null, MESSAGE); 
      return false; 
    } 
 
    //  If the destination directory name does not end with a file separator, add 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()) { 
      //  Delete the existing target directory if overwriting is allowed  
      if (overlay) { 
        new File(destDirName).delete(); 
      } else { 
        MESSAGE = " Failed to copy directory: 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(" Copy directory failed: create destination directory failed! "); 
        return false; 
      } 
    } 
 
    boolean flag = true; 
    File[] files = srcDir.listFiles(); 
    for (int i = 0; i < files.length; i++) { 
      //  Copy the file  
      if (files[i].isFile()) { 
        flag = 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 + " Failure! "; 
      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, the fastest way to copy single-threaded files is (the larger the file, the more advantages this method has, 1 generally 30+% faster than the common method):


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 buffer, which has a big impact on speed):


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); 
  } 
} 

Common 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); 
  } 
} 

Common 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); 
  } 
}


Related articles: