0

Using java how can I move a file from one directory to another? Should I just use streamReader to copy the bytes over to the destination directory then delete the original file?

1
  • check this link Commented Oct 7, 2011 at 18:31

8 Answers 8

2

Try the File.renameTo operation. Despite its name, it may also be used to move files around. However, be warned, that, as the documentation states, that its behaviour will depend on the platform you are running on.

Example:

File oldFile = ...;
File newDirectory = ...;
String newName = ...;
File newFile = new File(newDirectory, newName);

oldName.renameTo(newFile);
Sign up to request clarification or add additional context in comments.

Comments

2

That sounds wrong. If you're indeed moving the file (and not making a copy), then you should be using the much cheaper rename method of some sort. (File.renameTo()) seems to be the method recommended).

[Edit] The move operation in most (perhaps even... all) operating systems is much cheaper than a full copy and delete. It's equivalent to deleting the entry for the file in one directory and adding it to a different directory (or under a different name in the same directory). There's no need to touch the actual data in the file for this operation.

Comments

1

Or you can use Java NIO:

http://www.exampledepot.com/egs/java.nio/File2File.html

Comments

0

I suggest you use the FileUtils class from org.apache.common. Documentation here.

Comments

0

Instead of rolling your own, you could use something like the apache commons IO utilities.

Here you could just call FileUtils.copyFile

see here for details http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html

Comments

0

Try the copyFile method of the FileUtils class from the Apache commons-IO API.

It's been tested for you!

Comments

0

you can do a file renameTo and give it the new location of the file as the parameter.

See Here

Comments

0

First try File.renameTo() to do a real move. If that fails, do a real copy/delete. Besides of this: InputStream and OutputStream is the most basic way to do the copy. But if you don't want to reinvent the wheel you can use FileUtis to do exactly what I have described.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.