重命名android中的连续文件夹和文件

时间:2017-01-07 08:06:47

标签: java android android-file

我在a / b / c.txt位置有一个文件。我想将此文件移动到位置d / e / f.txt。我想将文件夹/目录a重命名为d,b为e,并将c.txt文件重命名为f.txt。如何在android中执行此操作?

public void moveFile(View view) {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "a" + File.separator + "b" + File.separator + "c.txt");
            if (file.exists()) {
                boolean res = file.renameTo(new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + File.separator + "d" + File.separator + "e" + File.separator + "f.txt"));


                Toast.makeText(MainActivity.this, String.valueOf(res), Toast.LENGTH_SHORT).show();
            }

        }

1 个答案:

答案 0 :(得分:1)

当你说“我想将文件夹/目录a重命名为d,b到e并将c.txt文件重命名为f.txt”时,你正走在正确的轨道上。你只需重命名一个目录。时间和文件本身分开:

    String externalStorageDirAbsPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(externalStorageDirAbsPath + File.separator + "a" + File.separator + "b" + File.separator + "c.txt");
    if (file.exists()) {
        // first rename a to d
        boolean res = new File(externalStorageDirAbsPath + File.separator + "a")
                        .renameTo(new File(externalStorageDirAbsPath + File.separator + "d"));
        if (res) {
            // rename b to e
            res = new File(externalStorageDirAbsPath + File.separator + "d" + File.separator + "b")
                    .renameTo(new File(externalStorageDirAbsPath + File.separator + "d" + File.separator + "e"));
            if (res) {
                // rename c.txt to f.txt
                res = new File(externalStorageDirAbsPath + File.separator + "d" + File.separator + "e" + File.separator + "c.txt")
                        .renameTo(new File(externalStorageDirAbsPath + File.separator + "d" + File.separator + "e" + File.separator + "f.txt"));
            }
        }
        Toast.makeText(MainActivity.this, String.valueOf(res), Toast.LENGTH_SHORT).show();
    }

我在Mac OS X上测试了代码的核心部分。我没有在Android上测试过。如果手动翻译中的拼写错误回到Android代码,我希望你能够弄明白。

您可能希望查看较新的File包,而不是java.nio.file类,Path类可能会给您带来一些便利,但我认为您仍需要一次重命名一个目录和文件,就像在这里一样。

相关问题