2012-02-03 50 views
3

我需要从一个位置上的用户SD卡将文件移动到另一个位置上的SD卡移动在Android上

目前,我与File.renameTo

例如这样一个文件从sdcard/test/one.txt到sdcard/test2/two.txt

某些用户报告文件移动功能不起作用。

How to copy files from 'assets' folder to sdcard?

那么什么是一个目录中的文件移动到另一个对SD卡的最佳方式:

我碰到下面的链接来了?

回答

3

尝试复制这些代码并检查文件并删除原来的文件。

private void backup(File sourceFile) 
{ 
    FileInputStream fis = null; 
    FileOutputStream fos = null; 
    FileChannel in = null; 
    FileChannel out = null; 

    try 
    { 
     File backupFile = new File(backupDirectory.getAbsolutePath() + seprator + sourceFile.getName()); 
     backupFile.createNewFile(); 

     fis = new FileInputStream(sourceFile); 
     fos = new FileOutputStream(backupFile); 
     in = fis.getChannel(); 
     out = fos.getChannel(); 

     long size = in.size(); 
     in.transferTo(0, size, out); 
    } 
    catch (Throwable e) 
    { 
     e.printStackTrace(); 
    } 
    finally 
    { 
     try 
     { 
      if (fis != null) 
       fis.close(); 
     } 
     catch (Throwable ignore) 
     {} 

     try 
     { 
      if (fos != null) 
       fos.close(); 
     } 
     catch (Throwable ignore) 
     {} 

     try 
     { 
      if (in != null && in.isOpen()) 
       in.close(); 
     } 
     catch (Throwable ignore) 
     {} 

     try 
     { 
      if (out != null && out.isOpen()) 
       out.close(); 
     } 
     catch (Throwable ignore) 
     {} 
    } 
} 
+0

感谢,那很好用 – user1177292 2012-02-03 22:29:46

0

为什么不能使用rename

File sd=Environment.getExternalStorageDirectory(); 
// File (or directory) to be moved 
String sourcePath="/.Images/"+imageTitle; 
File file = new File(sd,sourcePath); 
// Destination directory 
boolean success = file.renameTo(new File(sd, imageTitle)); 
0

我知道这个问题已经很久很久以前回答,但我发现拷贝整个文件是一个严酷的方法...... 这里是我做的,如果有人需要它:

static public boolean moveFile(String oldfilename, String newFolderPath, String newFilename) { 
    File folder = new File(newFolderPath); 
    if (!folder.exists()) 
     folder.mkdirs(); 

    File oldfile = new File(oldfilename); 
    File newFile = new File(newFolderPath, newFilename); 

    if (!newFile.exists()) 
     try { 
      newFile.createNewFile(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    return oldfile.renameTo(newFile); 
} 
+0

如果旧文件和新文件位于同一个安装点上,这将起作用。从[文档](http://developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29)“两个路径都在同一个挂载点上。” – Diederik 2014-08-01 09:28:14

+0

@Diederik是的,当然,你不能将文件从一个分区移动到另一个分区...... – TheSquad 2014-09-23 17:33:52