在SD卡中移动文件

3

我一直在尝试将文件移动到SD卡中,但一直没有成功。以下是代码:

try {
            File sd=Environment.getExternalStorageDirectory();
            // File (or directory) to be moved
            String sourcePath="mnt/sdcard/.Images/"+imageTitle;
            File file = new File(sd,sourcePath);
            // Destination directory
            String destinationPath="mnt/sdcard/"+imageTitle;
            File dir = new File(sd,destinationPath);

            // Move file to new directory
            boolean success = file.renameTo(new File(dir, file.getName()));
            if (!success) {
                handler.post(new Runnable(){
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "File moved", Toast.LENGTH_LONG).show();
                    }
                });
            }

        } 
        catch (Exception e) {
        }

我不知道怎么回事,希望能得到帮助。


什么出了问题?Logcat?Stacktrace? - eldarerathis
还有一些注意事项。尽量避免捕获通用异常。而且你的文件路径并不是以根目录开头的。 - muffinmad
1个回答

12

首先,如果你已经得到了外部目录,就没有必要把它添加到sourcepathdestinationpath的开头。

第二,看起来destinationPath是不必要的,因为你只想把它移动到sdcard的根目录。

代码应该是这样的:

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

1
请注意,目标文件夹需要存在。File.mkdirs可以派上用场。 - ılǝ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接