简体   繁体   中英

Java: copy files between directories

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?

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);

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.

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

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

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

It's been tested for you!

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

See Here

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM