首页 > 解决方案 > 如何使用 File.move()

问题描述

我想将文件从下载文件夹移动到我的应用程序中的文件夹,我看到您可以使用 Files.move (source, destination) 功能,但我不知道如何获取源和目标路径.

当你尝试

 String sdCard = Environment.getExternalStorageDirectory().toString();
 File ficheroPrueba = new File(sdCard + "/pau_alem18je_compressed.pdf");

 if(ficheroPrueba.exists())
           Log.v(TAG, "Hola")
 }

尽管已经下载了文件(在 android 模拟器的下载中可以看到),但它不会打印 log.v

标签: javaandroid

解决方案


使用 Environment.getExternalStorageDirectory() 获取外部存储的根目录(在某些设备上,它是 SD 卡)。

String sdCard = Environment.getExternalStorageDirectory().toString();

    // the file to be moved or copied
    File sourceLocation = new File (sdCard + "/sample.txt");

    // make sure your target location folder exists!
    File targetLocation = new File (sdCard + "/MyNewFolder/sample.txt");

    // just to take note of the location sources
    Log.v(TAG, "sourceLocation: " + sourceLocation);
    Log.v(TAG, "targetLocation: " + targetLocation);

    try {

        // 1 = move the file, 2 = copy the file
        int actionChoice = 2;

        // moving the file to another directory
        if(actionChoice==1){

            if(sourceLocation.renameTo(targetLocation)){
                Log.v(TAG, "Move file successful.");
            }else{
                Log.v(TAG, "Move file failed.");
            }

        }

        // we will copy the file
        else{

            // make sure the target file exists

            if(sourceLocation.exists()){

                InputStream in = new FileInputStream(sourceLocation);
                OutputStream out = new FileOutputStream(targetLocation);

                // Copy the bits from instream to outstream
                byte[] buf = new byte[1024];
                int len;

                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                in.close();
                out.close();

                Log.v(TAG, "Copy file successful.");

            }else{
                Log.v(TAG, "Copy file failed. Source file missing.");
            }

        }

    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


推荐阅读