How can I move files to another folder with java?
Solution 1
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();
Solution 2
Commons-io has a few methods in the FileUtils class that can help you.
Example: FileUtils.moveFile(src, dest);
Solution 3
The usual approach to solving this is copying the file and then deleting it from the original location, but you can follow this tutorial for more information. Also, the platform(linux, windows, is not important).
Solution 4
I didn't run this, but it should work
File f1 = new File("/home/folder1/image.png");
File f2 = new File("/home/folder1/folder2/image.png");
f1.renameTo(f2);
Solution 5
There are many approaches for you to do that. This snippet is one of them, you can move your files like this way:
try {
final File myFile = new File("C:\\folder1\\myfile.txt");
if(myFile.renameTo(new File("C:\\folder2\\" + myFile.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
Related videos on Youtube
Sebastian Tare B.
I like Robots, Science Fiction, Anime, and Video Games. Currently I'm doing a master in Computer Science at Universidad del Bío-Bío.
Updated on October 30, 2022Comments
-
Sebastian Tare B. over 1 year
I want to move files (images) from a folder to another:
For example:
/home/folder1/image.png
to
/home/folder1/folder2/image.png
And obviously remove the image from the folder1
I've trying to do it by reading the path and then modifying it, or using renameTo, but i can't do it.
I hope someone can help me a little with this, Thanks.
EDIT:
Well I can put the code but it's simple to explain what i did:
I just created a Folder class that has a File object of my folder (/home/folder1) , i read all the images inside and save it in an File array, then i scan it and try to change the path of every image file String to another
EDIT:
Thanks to all for the help, all are good examples, I was able to change my files to another location, there was a bunch of files I wanted to move so, I didn't want to create too many objects.
-
Reti43 over 9 yearsAnd the code you've used for that.
-
colti over 9 yearsEasily done with Apache FileUtils
moveFile
method: commons.apache.org/proper/commons-io/apidocs/org/apache/commons/…
-
-
Leos Literak over 6 yearsrenameTo has a limitation to same physical disk. so moving between disk will fail.