Java rename file in folder

Java Guides

Java comes with renameTo() method to rename a file. However, this method is really platform-dependent: you may successfully rename a file in *nix but failed in Windows. So, the return value (true if the file renames successful, false if failed) should always be checked to make sure the file is renamed successfully.

2. Rename File Example

  1. Create a file named «sample.txt» in directory «C:/workspace».
  2. Create File class object by passing file absolute location path «C:/workspace/sample.txt».
  3. We need to passs new abstract pathname to renameTo() method to rename the file.
  4. renameTo() method returns true if and only if the renaming succeeded; false otherwise.
  5. Observe the directory whether the file is renamed or not.
import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This Java program demonstrates how to rename existing file in Java. * @author javaguides.net */ public class RenameFileExample < private static final Logger LOGGER = LoggerFactory.getLogger(DeleteFileExample.class); public static void main(String[] args) < renameFile(); >// Renames the file denoted by this abstract pathname. public static void renameFile() < File file = new File("C:/workspace/sample.txt"); boolean hasRename = file.renameTo(new File("C:/workspace/sample2.txt")); if (hasRename) < LOGGER.info("File rename successful"); > else < LOGGER.info("File reanme failed"); > > >

Источник

Читайте также:  Java reflect array type

How to rename/move file or directory in Java

To rename or move a file/directory in Java, you can use either the renameTo() method of a File object in the old File I/O API, or the Files.move() method in the new Java NIO API.

1. Rename File/Directory Example with renameTo() method

The following example renames a file to a new name in the current directory:

File sourceFile = new File(«Notes.txt»); File destFile = new File(«Keynotes.txt»); if (sourceFile.renameTo(destFile)) < System.out.println("File renamed successfully"); >else

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»); File destFile = new File(«dist»); if (sourceFile.renameTo(destFile)) < System.out.println("Directory renamed successfully"); >else

2. Move File Example with renameTo() method

If the path of the destination File points to another directory, the source file will be moved. The following example moves a file from the current directory to another one (also renames it):

File sourceFile = new File(«CoverPhoto.png»); File destFile = new File(«D:/Photo/ProfilePhoto.png»); if (sourceFile.renameTo(destFile)) < System.out.println("File moved successfully"); >else
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. So it is recommended to use the Files.move() method in Java NIO as described below.

3. Rename File/Directory Example with Files.move() method

The static move() method of the Files class in the java.nio.file 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"); Files.move(source, source.resolveSibling("Keynotes.txt"));

If the target file exists, this method throws java.nio.file.FileAlreadyExistsException . You can specify the option to replace the existing file like this:

Path source = Paths.get("Notes.txt"); Files.move(source, source.resolveSibling("Keynotes.txt"), StandardCopyOption.REPLACE_EXISTING);
Path source = Paths.get("photo"); Files.move(source, source.resolveSibling("photos"));

If the target dir exists, it throws FileAlreadyExistsException . You can fore to replace the existing directory with the copy option:

Path source = Paths.get("photo"); Files.move(source, source.resolveSibling("photos"), StandardCopyOption.REPLACE_EXISTING);

However, this works only if the target directory is not empty. Otherwise, it throws java.nio.file.DirectoryNotEmptyException .

4. Move File/Directory Example with Files.move() method

The following example illustrates how to move a file from the current directory to another (keeping the same file name) and replace the existing file:

Path source = Paths.get("CoverPhoto.png"); Path newdir = Paths.get("D:/Photo"); Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
Path source = Paths.get("test"); Path newdir = Paths.get("D:/Photo"); Files.move(source, newdir.resolve(source.getFileName()));

NOTE: You can move only empty directory and replace existing directory if it is also empty. In either a directory is not empty, a DirectoryNotEmptyException is thrown.

API References:

Other Java File IO Tutorials:

  • How to Read and Write Text File in Java
  • How to Read and Write Binary Files in Java
  • Java IO — Common File and Directory Operations Examples
  • Java Serialization Basic Example
  • Understanding Java Externalization with Examples
  • How to execute Operating System Commands in Java
  • 3 ways for reading user’s input from console in Java
  • File change notification example with Watch Service API
  • Java Scanner Tutorial and Code Examples
  • How to compress files in ZIP format in Java
  • How to extract ZIP file in Java

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Rename or Move a File or Directory in Java

Learn to rename a file or directory at a specified path or move to a new directory in Java. We will learn to use the classes from Standard IO, New IO, Guava and Commons IO.

As the method name suggests, renameTo() renames the file to the new name or moves the file to a new directory location.

  • The renameTo() returns true or false denoting if the renaming succeeded or not.
  • It throws SecurityException if there are write access problems with the old or the new file.
File originalFile = new File("c:/temp/demo.txt"); File renamedFile = new File("c:/temp/demoNew.txt"); File movedFile = new File("c:/temp/moved/demoNew.txt"); boolean isCopied = originalFile.renameTo(renamedFile); boolean isMoved = renamedFile.renameTo(movedFile); System.out.println(isCopied); //true System.out.println(isMoved); //true

The Files.move() is similar to renameTo() except it works with the Path instances instead of File instances.

  • The move() method moves or renames a file to a target file. Moving a file will copy the last-modified-time to the target file if supported
  • If given file and target files are same then this method has no effect.
  • If target file already exists then move() will fail. We can use StandardCopyOption.REPLACE_EXISTING in such cases.
  • To perform the whole rename or move operation as single atomic operation, we can use StandardCopyOption.ATOMIC_MOVE option. If the move cannot be performed as an atomic file system operation (incase of two different filesystems) then AtomicMoveNotSupportedException is thrown.
  • If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved.
  • Renaming a directory can fail if it requires to move the files in a new location i.e. directory is being moved to a location. It it is a simple directory renaming in same location in the filesystem, it will succeed.
Path file = Path.of("c:/temp/demo.txt"); //Rename in same directory Files.move(file, file.resolveSibling("demoNew.txt")); //Move to new directory Path newDir = Path.of("c:/temp/moved/"); Files.move(file, newDir.resolve(file.getFileName()), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);

This Files.move() method moves a file from one path to another. This is applicable to renaming and moving, both operations.

We should be careful that the destination path must be the target path for the file itself; not just the new name for the file or the path to the new parent directory.

File originalFile = new File("c:/temp/demo.txt"); File renamedFile = new File("c:/temp/demoNew.txt"); com.google.common.io.Files.move(originalFile, renamedFile); com.google.common.io.Files.move(renamedFile, movedFile);

The FileUtils class provides many methods to move or rename the files and directories as per requirements.

  • moveDirectory(File srcDir, File destDir) – moves a directory to destination and deletes the source directory.
  • moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) : Moves a directory to another directory and takes an option to create the new directory or not. If createDestDir is false and new directory cannot be created then IOException will be thrown.
  • moveFile(File srcFile, File destFile, CopyOption… copyOptions) : moves a file preserving file attributes with optional copy options.
  • moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) : moves a file into a specified directory.
  • moveToDirectory(File src, File destDir, boolean createDestDir) : moves a file or directory to the destination directory.
FileUtils.moveFile(originalFile, renamedFile); File targetDirectory = new File("c:/temp/moved/"); FileUtils.moveFileToDirectory(originalFile, targetDirectory, true);

In this short tutorial, we learned to rename a file or directory or move it to a new location with different copy options.

Though standard IO and new IO classes provide all kinds of capabilities, Common IO’s FileUtils class provides very specific methods for each kind of operation. These specific method names communicate the intent very well.

Источник

Оцените статью