Java replace file path

How to rename or move a file in Java

In Java, we can use the NIO Files.move(source, target) to rename or move a file.

 import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; //. Path source = Paths.get("/home/mkyong/newfolder/test1.txt"); Path target = Paths.get("/home/mkyong/newfolder/test2.txt"); try < Files.move(source, target); >catch (IOException e)

1. Rename a file in the same directory.

1.1 This example renames a file in the same directory, keeping the same file name.

 Path source = Paths.get("/home/mkyong/hello.txt"); try < // rename a file in the same directory Files.move(source, source.resolveSibling("newName.txt")); >catch (IOException e)

1.2 If the target file exists, the Files.move throws FileAlreadyExistsException .

 java.nio.file.FileAlreadyExistsException: /home/mkyong/newName.txt at java.base/sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:450) at java.base/sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:267) at java.base/java.nio.file.Files.move(Files.java:1421) at com.mkyong.io.file.FileRename.main(FileRename.java:26) 

1.3 If the REPLACE_EXISTING option is specified, and the target file exists, the Files.move will replace it.

 import java.nio.file.StandardCopyOption; Files.move(source, source.resolveSibling("newName.txt"), StandardCopyOption.REPLACE_EXISTING); 

2. Move a file to a new directory.

2.1 This example moves a file to a new directory, keeping the same file name. If the target file exists, replace it.

 Path source = Paths.get("/home/mkyong/hello.txt"); Path newDir = Paths.get("/home/mkyong/newfolder/"); //create the target directories, if directory exits, no effect Files.createDirectories(newDir); Files.move(source, newDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING); 

2.2 If target directory not exits, the Files.move throws NoSuchFileException .

 java.nio.file.NoSuchFileException: /home/mkyong/hello.txt -> /home/mkyong/newfolder/hello2.txt at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92) at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111) at java.base/sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:478) at java.base/sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:267) at java.base/java.nio.file.Files.move(Files.java:1421) at com.mkyong.io.file.FileRename.main(FileRename.java:23) 

3. Move file – Apache Commons IO

3.1 The Apache FileUtils.moveFile uses a «copy and delete» mechanism to rename or move a file. Furthermore, it did a lot of checking and ensuring the correct exception is thrown, a reliable solution.

 import org.apache.commons.io.FileUtils; //. File source = new File("/home/mkyong/hello.txt"); File target = new File("/home/mkyong/newfolder/hello2.txt"); try < FileUtils.moveFile(source, target); >catch (IOException e)

3.2 If the target file exists, it throws FileExistsException .

 org.apache.commons.io.FileExistsException: Destination '/home/mkyong/newfolder/hello2.txt' already exists at org.apache.commons.io.FileUtils.moveFile(FileUtils.java:2012) at com.mkyong.io.file.FileRename.main(FileRename.java:39) 

3.3 If the target directory does not exist, create it.

4. File.renameTo (Legacy IO)

The legacy IO File.renameTo() is not reliable, not recommend to use, read the api documentation.

If the File.renameTo() failed to rename or move the file, it will return a false, no exception thrown, often time, we have no idea what went wrong.

Download Source Code

References

Источник

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.

Источник

Читайте также:  Html email signature generator
Оцените статью