【问题标题】:How to use File.move ()如何使用 File.move()
【发布时间】:2019-09-04 20:17:00
【问题描述】:

我想将文件从下载文件夹移动到我的应用程序中的文件夹,我看到你可以使用 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")
 }

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

【问题讨论】:

  • 我试过了但是没办法,我已经在主文中解释过了(我已经在主文中更新了)@DmytroBatyuk

标签: java android


【解决方案1】:

使用 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();
    }
}

【讨论】:

  • 我有这个 sourceLocation: /storage/emulated/0/Download/pau_alem18je_compressed.pdf 和这个 storageLocation /storage/emulated/0app/src/main/assets/pau_alem18je_compressed.pdf 但代码没有移动 pdf @SumanDash
猜你喜欢
  • 1970-01-01
  • 2011-10-25
  • 2011-02-13
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
  • 2017-04-13
相关资源
最近更新 更多