我在位置 a/b/c 有一个文件.txt .我想将此文件移动到位置 d/e/f.txt 。我想将文件夹/目录 a 重命名为 d,b 重命名为 e,将文件 c.txt 重命名为 f.txt 。如何在安卓中做到这一点?
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();
}
}
当你说"我想将文件夹/目录 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代码有错别字,我希望你能弄清楚。
与您可能想要查看较新的java.nio.file
包的 File
类不同,Path
类可能会在这里为您提供一些便利,但我认为您仍然必须一次重命名一个目录并单独重命名文件,就像这里一样。