Thi*_*ilo 115
myFile.renameTo(new File("/the/new/place/newName.file"));
Run Code Online (Sandbox Code Playgroud)
File#renameTo可以做到这一点(它不仅可以重命名,还可以在目录之间移动,至少在同一个文件系统上).
重命名此抽象路径名表示的文件.
此方法行为的许多方面本质上依赖于平台:重命名操作可能无法将文件从一个文件系统移动到另一个文件系统,它可能不是原子的,如果具有目标抽象路径名的文件可能不会成功已经存在.应始终检查返回值以确保重命名操作成功.
如果您需要更全面的解决方案(例如想要在磁盘之间移动文件),请查看Apache Commons FileUtils #moveverFile
mic*_*cha 60
使用Java 7或更高版本,您可以使用Files.move(from, to, CopyOption... options)
.
例如
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅文件文档
爪哇 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Run Code Online (Sandbox Code Playgroud)
Java 7(使用 NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
Run Code Online (Sandbox Code Playgroud)
只需添加源和目标文件夹路径。
它将所有文件和文件夹从源文件夹移动到目标文件夹。
File destinationFolder = new File("");
File sourceFolder = new File("");
if (!destinationFolder.exists())
{
destinationFolder.mkdirs();
}
// Check weather source exists and it is folder.
if (sourceFolder.exists() && sourceFolder.isDirectory())
{
// Get list of the files and iterate over them
File[] listOfFiles = sourceFolder.listFiles();
if (listOfFiles != null)
{
for (File child : listOfFiles )
{
// Move files to destination folder
child.renameTo(new File(destinationFolder + "\\" + child.getName()));
}
// Add if you want to delete the source folder
sourceFolder.delete();
}
}
else
{
System.out.println(sourceFolder + " Folder does not exists");
}
Run Code Online (Sandbox Code Playgroud)