![]() You can specify the option to replace the existing file like this: Path source = Paths.get("Notes.txt") įiles.move(source, source.resolveSibling("Keynotes.txt"), Rename File/Directory Example with Files.move() methodThe static move() method of the Files class in the package is platform-independent and have options to replace the destination file if exists: Files.move(Path source, Path target, CopyOptions… options)This method returns the path to the target file, and throws exception if the operation failed.The following example renames a file in the current directory: Path source = Paths.get("Notes.txt") įiles.move(source, source.resolveSibling("Keynotes.txt")) If the target file exists, this method throws. So it is recommended to use the Files.move() method in Java NIO as described below. } NOTE: You cannot use the renameTo() method to move directory, even the directory is empty.This method is platform-dependent and is not guaranteed to work in all cases. ![]() The following example moves a file from the current directory to another one (also renames it): File sourceFile = new File("CoverPhoto.png") įile destFile = new File("D:/Photo/ProfilePhoto.png") If the path of the destination File points to another directory, the source file will be moved. ![]() }If the destination directory exists, the method return false. }As you can see in this example, the renameTo() method returns a boolean value indicating the renaming succeeded (true) or failed (false) - so you should always check its return value.If the destination file exists, the method returns false.The following example renames the directory “test” to “dist” in the current directory: File sourceFile = new File("test") Rename File/Directory Example with renameTo() methodYou can use the renameTo() method to rename a file or directory to a new name which does not exist.The following example renames a file to a new name in the current directory: File sourceFile = new File("Notes.txt") įile destFile = new File("Keynotes.txt") To rename or move a file/directory in Java, you can use either the renameTo() method of a Fileobject in the old File I/O API, or the Files.move() method in the new Java NIO API.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |