Android 中 復制文件的方法


a)首先要把權限加到AndroidManifest.xml當中

  

  b)創建一個類,將下面的代碼復制進去

  public static void copyfile(File fromFile, File toFile,Boolean rewrite )

  {

  if (!fromFile.exists()) {

  return;

  }

  if (!fromFile.isFile()) {

  return ;

  }

  if (!fromFile.canRead()) {

  return ;

  }

  if (!toFile.getParentFile().exists()) {

  toFile.getParentFile().mkdirs();

  }

  if (toFile.exists() && rewrite) {

  toFile.delete();

  }

  當文件不存時,canWrite一直返回的都是false

  // if (!toFile.canWrite()) {

  // MessageDialog.openError(new Shell(),"錯誤信息","不能夠寫將要復制的目標文件" + toFile.getPath());

  // Toast.makeText(this,"不能夠寫將要復制的目標文件", Toast.LENGTH_SHORT);

  // return ;

  // }

  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) {

  Log.e("readfile", ex.getMessage());

  }

  }

  c) 調用方法

  File fromFile=new File("/sdcard/MyFile.txt");

  File toFile=new File("/sdcard/xx.txt");

  copyfile(fromFile, toFile, true);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM