Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I move files to another folder with java?

Tags:

java

file

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.

like image 978
Sebastian Tare B. Avatar asked Jan 13 '15 21:01

Sebastian Tare B.


People also ask

How do I save a file to a specific directory in Java?

Try something like this: File file = new File("/some/absolute/path/myfile. ext"); OutputStream out = new FileOutputStream(file); // Write your data out. close();


2 Answers

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();
like image 52
haley Avatar answered Oct 12 '22 23:10

haley


Commons-io has a few methods in the FileUtils class that can help you.

http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html?org/apache/commons/io/package-summary.html

Example: FileUtils.moveFile(src, dest);

like image 42
Matt Avatar answered Oct 12 '22 23:10

Matt