Move one file to another directory in java

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.

Источник

How to move file to another directory in Java

This article shows how to move a file to another directory in the same file drive or remote server.

1. Move file to another directory

This Java example uses NIO Files.move to move a file from to another directory in the same local drive.

 package com.mkyong.io.file; import java.io.IOException; import java.nio.file.*; public class FileMove < public static void main(String[] args) < String fromFile = "/home/mkyong/data/db.debug.conf"; String toFile = "/home/mkyong/data/deploy/db.conf"; Path source = Paths.get(fromFile); Path target = Paths.get(toFile); try < // rename or move a file to other path // if target exists, throws FileAlreadyExistsException Files.move(source, target); // if target exists, replace it. // Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); // multiple CopyOption /*CopyOption[] options = < StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES, LinkOption.NOFOLLOW_LINKS >; Files.move(source, target, options);*/ > catch (IOException e) < e.printStackTrace(); >> > 

2. Move file to remote server directory

This Java example uses JSch library to move a file from the local system to another directory in a remote server, using SFTP.

P.S Assume the remote server is enabled SSH login (default port 22) using a password.

 package com.mkyong.io.howto; import com.jcraft.jsch.*; public class SFTPFileTransfer < private static final String REMOTE_HOST = "1.2.3.4"; private static final String USERNAME = ""; private static final String PASSWORD = ""; private static final int REMOTE_PORT = 22; private static final int SESSION_TIMEOUT = 10000; private static final int CHANNEL_TIMEOUT = 5000; public static void main(String[] args) < // local String localFile = "/home/mkyong/hello.sh"; // remote server String remoteFile = "/home/mkyong/test.sh"; Session jschSession = null; try < JSch jsch = new JSch(); jsch.setKnownHosts("/home/mkyong/.ssh/known_hosts"); jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT); // authenticate using private key // jsch.addIdentity("/home/mkyong/.ssh/id_rsa"); // authenticate using password jschSession.setPassword(PASSWORD); // 10 seconds session timeout jschSession.connect(SESSION_TIMEOUT); Channel sftp = jschSession.openChannel("sftp"); // 5 seconds timeout sftp.connect(CHANNEL_TIMEOUT); ChannelSftp channelSftp = (ChannelSftp) sftp; // transfer file from local to remote server channelSftp.put(localFile, remoteFile); // download file from remote server to local // channelSftp.get(remoteFile, localFile); channelSftp.exit(); >catch (JSchException | SftpException e) < e.printStackTrace(); >finally < if (jschSession != null) < jschSession.disconnect(); >> > > 

Note
The NIO Files.move can’t move a file from the local system to a remote server directory.

Download Source Code

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

how to copy a file from one folder to another
using sftp protocol in java

We updated the article with SFTP examples, more examples in below link.

need your assistance to navigate different directory in unix using java program

How you want to navigate, try Paths ?

Now-a-days you will want to use this:

“Files.move(source, target, REPLACE_EXISTING);”

I think this will not move files between drives. Nevermind, it does for me.

i have files few files in dir Screenshots i want to create new Dir in screenshots and move all files to that dir . how we can achieve this

If it involves multiple files, try FileVisitor

hi i want to move files from one folder to other in sftp using java in sprigboot can you help me with that?

How we can move yesterday date file into other directory?

Hi mkyong,
I want to copy a file from one folder to another, and the same file need to move to another folder. Please guide.

Hi,I use the same code but when I used the first code It told me “File is failed to move”,when I used the second code it was saying “java.io.FileNotFoundException”, was it due to a mismatch between wins and java character rules?
Anyway,thank you for your answer.

Try NIO Files.move , it will return the correct exception.

This can be achieved thro’ JSP?If so please share the Codes

Hi same code is not working for FTP server,
I want to move some zip files from FTP server to local drive.

Try JSch library to move files to remote server directory.

File wallpaperDirectory3 = new File(“/sdcard/Download/Scan1.jpg”);

boolean success = wallpaperDirectory3.renameTo(new File(

Toast.makeText(getApplicationContext(), “” + success, Toast.LENGTH_LONG)

The legacy fie.renameTo will not throw exception if operation failed. Try Files.move

hi i used this code to move file from one directory to another in android, but it is not working

why not using “java.nio.file.StandardCopyOption” ?

well I’m looking for easy and effective way for moving whole folder to other location(can be on different filesystem or the same one) and found the “Files.move()” method from the Java documentation

You cannot import it in Android.

did the same code works for android emulator?

Indeed, there’s an API to move files:

I have two files in the directory, the first one fails but the second is successful when using renameTo. Why is it like that?

Hi, thanks for the information about java in your web site! Great work!

Can you copy a File Video…Example: copy a video From C:\\ To D:\\ (OS)

hi i tried to copy an image and video files using the same code and it worked.

my query is … how can i run this file movo java code in browser using javascript?

Run Java code in browser using JavaScript!? I’m not sure what is your use case, it is better rewrite the Java code in JavaScript.

Hello i am very much interested in java and it’s technologies . i found lots of new things from your blog

how to upload file to a network drive in oracle 10g?

If SSH is allowed, try JSch library, please visit the below example.

hello sir
it’s to move a text file.
How can i move a file other than .txt ?
like .RAR , or any video/audio file.

Good exercise. In the copy & delete example, it would be good to use “deleteOnExit()”. If we use “delete()” the source file might be still in use and may not get deleted.

Thanks for this tutorial. I gave this a shot such that I am calling it in a loop and iterating over serveral files in a directory to be moved to a new location. It did the move of all the files perfectly. However, only one file was actually deleted. Is there something that must be added in order to get it to delete the files in the source directly with successive calls to this function? Your thought would be much appreciated.

Источник

How to move a file to another directory in Java

In this quick article, you’ll learn how to move a file from one directory to another directory in Java.

In Java 7 and higher, you can use the Files.move() static method from Java NIO API to easily move a file from one location to another location as shown below:

try  // source & destination files Path src = Paths.get("dir1/input.txt"); Path target = Paths.get("dir2/input.txt"); // move file fron one location to another Files.move(src, target, StandardCopyOption.REPLACE_EXISTING); > catch (IOException ex)  ex.printStackTrace(); > 

In older Java versions (Java 6 and below), you can call the renameTo() method on a File object to move file from one directory to another directory as shown below:

// source & destination files File src = new File("dir1/input.txt"); File target = new File("dir2/input.txt"); // move file fron one location to another if (src.renameTo(target))  System.out.println("File is moved."); > else  System.out.println("File failed to move!"); > 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Moving a File or Directory

You can move a file or directory by using the move(Path, Path, CopyOption. ) method. The move fails if the target file exists, unless the REPLACE_EXISTING option is specified.

Empty directories can be moved. If the directory is not empty, the move is allowed when the directory can be moved without moving the contents of that directory. On UNIX systems, moving a directory within the same partition generally consists of renaming the directory. In that situation, this method works even when the directory contains files.

This method takes a varargs argument – the following StandardCopyOption enums are supported:

  • REPLACE_EXISTING – Performs the move even when the target file already exists. If the target is a symbolic link, the symbolic link is replaced but what it points to is not affected.
  • ATOMIC_MOVE – Performs the move as an atomic file operation. If the file system does not support an atomic move, an exception is thrown. With an ATOMIC_MOVE you can move a file into a directory and be guaranteed that any process watching the directory accesses a complete file.

The following shows how to use the move method:

import static java.nio.file.StandardCopyOption.*; . Files.move(source, target, REPLACE_EXISTING);

Though you can implement the move method on a single directory as shown, the method is most often used with the file tree recursion mechanism. For more information, see Walking the File Tree.

Previous page: Copying a File or Directory
Next page: Managing Metadata (File and File Store Attributes)

Источник

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