copy file, make folder if necessary - Android java.io

Android examples for java.io:File Copy

Description

copy file, make folder if necessary

Demo Code

import java.io.File;
import java.io.FileOutputStream;

public class Main {

  public static String copyfile(String fromPath, String toPath, Boolean rewrite) {
    File fromFile = new File(fromPath);
    File toFile = new File(toPath);
    if (!fromFile.exists()) {
      return null;
    }//  ww  w. j  ava 2s  .  c om
    if (!fromFile.isFile()) {
      return null;
    }
    if (!fromFile.canRead()) {
      return null;
    }
    if (!toFile.getParentFile().exists()) {
      toFile.getParentFile().mkdirs();
    }
    if (toFile.exists() && rewrite) {
      toFile.delete();
    }
    try {
      java.io.FileInputStream fosfrom = new java.io.FileInputStream(fromFile);
      java.io.FileOutputStream fosto = new FileOutputStream(toFile);
      byte bt[] = new byte[1024];
      int c;
      while ((c = fosfrom.read(bt)) > 0) {
        fosto.write(bt, 0, c); 
      }
      fosfrom.close();
      fosto.close();
    } catch (Exception ex) {
    
    }
    return toPath;
  }

}

Related Tutorials