How do I move a file from one location to another in Java?
myFile.renameTo(new File("/the/new/place/newName.file"));
File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile
How can I move files to another folder with java?
You said you tried renameTo and it didn't work, but this worked for me. After I renamed it I deleted the original file.
File a = new File("C:\\folderA\\A.txt");
a.renameTo(new File("C:\\folderB\\" + a.getName()));
a.delete();
How to move list of files to some directory
try this code :
before proceeding to code we have to import appropriate java packages.Like this :
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.*;
Now we move to coding part, at first we have to specify the path of the folder from which we are going to move the files to do that :
String str_source = "D:\\temp";
Then We are going to specify the path of the folder in which we are going to move the files. To do that :
String str_target = "D:\\temp1\\";
Then We are listing out all the files from the original folder. To do this :
1. have to pass original folder name to the file object.
2. get list of files into the file array from the folder using that object.
File directory = new File(str_source);
File[] filesList = directory.listFiles();
Then we have to move files from one folder to the another folder.
Path result = null;
try
{
for(File file:filesList)
{
result = Files.move(Paths.get(file.getPath().toString()), Paths.get(str_target+file.getName().toString()));
}
}
catch(IOException e)
{
System.out.println("Exception while moving file: " + e.getMessage());
}
if(result != null)
{
System.out.println("File moved successfully.");
}
else
{
System.out.println("File movement failed.");
}
Entire Code look like :
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.*;
public class filemovetest {
public static void main(String[] args)
{
String str_source = "D:\\temp";
String str_target = "D:\\temp1\\";
File directory = new File(str_source);
File[] filesList = directory.listFiles();
for(File file:filesList)
{
System.out.println(file.getPath());
}
Path result = null;
try
{
for(File file:filesList)
{
result = Files.move(Paths.get(file.getPath().toString()), Paths.get(str_target+file.getName().toString()));
}
}
catch (IOException e)
{
System.out.println("Exception while moving file: " + e.getMessage());
}
if(result != null)
{
System.out.println("File moved successfully.");
}
else
{
System.out.println("File movement failed.");
}
}
}
Hope This will help you out :)
How to move the file in specified folder in java?
You can simply use Files.move
: https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...)
Move or rename a file to a target file.
By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException). To move a file tree may involve copying rather than moving directories and this can be done using the copy method in conjunction with the Files.walkFileTree utility method.
Path sourcePath = Paths.get("sourceFile.txt");
Path targetPath = Paths.get("targetFolder\\" + sourcePath.getFileName());
Files.move(sourcePath, targetPath);
Moving files from one directory to another with Java NIO
Files.move
is not equivalent to the mv
command. It won't detect that the destination is a directory and move files into there.
You have to construct the full destination path, file by file. If you want to copy /src/a.txt
to /dest/2014/
, the destination path needs to be /dest/2014/a.txt
.
You may want to do something like this:
File srcFile = new File("/src/a.txt");
File destDir = new File("/dest/2014");
Path src = srcFile.toPath();
Path dest = new File(destDir, srcFile.getName()).toPath(); // "/dest/2014/a.txt"
How to copy file from one location to another location?
You can use this (or any variant):
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Also, I'd recommend using File.separator
or /
instead of \\
to make it compliant across multiple OS, question/answer on this available here.
Since you're not sure how to temporarily store files, take a look at ArrayList
:
List<File> files = new ArrayList();
files.add(foundFile);
To move a List
of files into a single directory:
List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
Files.copy(file.toPath(),
(new File(path + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
Java - Move and Rename all files from one destination to another
You can use file.renameto()
for moving and renaming.
Sample -
import java.io.File;
public class MoveFileExample
{
public static void main(String[] args)
{
try{
File afile =new File("C:\\folderA\\Afile.txt");
if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Related Topics
Java Comparator Class to Sort Arrays
How to Increase Ide Memory Limit in Intellij Idea on MAC
How to Find a Whole Word in a String in Java
Java.Lang.Illegalaccesserror: Tried to Access Method
Is String Literal Pool a Collection of References to the String Object, or a Collection of Objects
Executors.Newcachedthreadpool() Versus Executors.Newfixedthreadpool()
In Java, When Should I Create a Checked Exception, and When Should It Be a Runtime Exception
How to Read All of Inputstream in Server Socket Java
Why Can't Primitive Data Types Be "Null" in Java
What Is the Point of Setters and Getters in Java
Does Java Have Built in Libraries for Audio _Synthesis_
How to Simulate a Buffered Peripheral Device with Swingworker
The Method Getdispatchertype() Is Undefined for the Type Httpservletrequest
How Do Different Retention Policies Affect My Annotations
When Should I Use an Interface in Java