Java:在目录之间复制文件
使用java如何将文件从一个目录移动到另一个目录?我应该使用streamReader 将字节复制到目标目录然后删除原始文件吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
尝试 < code>File.renameTo 操作。尽管它的名字如此,它也可用于移动文件。但是,请注意,正如文档所述,其行为将取决于您所运行的平台。
例子:
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.renameTo())似乎是推荐的方法)。
[编辑] 大多数(也许甚至...所有)操作系统中的移动操作比完整复制和删除便宜得多。它相当于删除一个目录中的文件条目并将其添加到不同的目录(或同一目录中的不同名称)。此操作无需触及文件中的实际数据。
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.
或者您可以使用 Java NIO:
http://www.exampledepot.com/egs/ java.nio/File2File.html
Or you can use Java NIO:
http://www.exampledepot.com/egs/java.nio/File2File.html
我建议您使用 org.apache.common 中的 FileUtils 类。文档此处。
I suggest you use the
FileUtils
class fromorg.apache.common
. Documentation here.您可以使用 apache commons IO 实用程序之类的东西,而不是自己动手。
这里你可以直接调用
FileUtils.copyFile
查看这里了解详细信息
http://commons.apache.org/io/apidocs /org/apache/commons/io/FileUtils.html
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
尝试 copyFile FileUtils 来自 Apache commons-IO API 的类。
已经为你测试过了!
Try the copyFile method of the FileUtils class from the Apache commons-IO API.
It's been tested for you!
您可以执行文件 renameTo 并将文件的新位置作为参数。
参见此处
you can do a file renameTo and give it the new location of the file as the parameter.
See Here
首先尝试
File.renameTo()
进行真正的移动。如果失败,请进行真正的复制/删除。除此之外:InputStream
和OutputStream
是最基本的复制方式。但如果你不想重新发明轮子,你可以使用 FileUtis 完全按照我所描述的操作。First try
File.renameTo()
to do a real move. If that fails, do a real copy/delete. Besides of this:InputStream
andOutputStream
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.