用Java将文件从一个目录复制到另一个目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1146153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copying files from one directory to another in Java
提问by user42155
I want to copy files from one directory to another (subdirectory) using Java. I have a directory, dir, with text files. I iterate over the first 20 files in dir, and want to copy them to another directory in the dir directory, which I have created right before the iteration.
In the code, I want to copy the review
(which represents the ith text file or review) to trainingDir
. How can I do this? There seems not to be such a function (or I couldn't find). Thank you.
我想使用 Java 将文件从一个目录复制到另一个(子目录)。我有一个带有文本文件的目录 dir。我遍历 dir 中的前 20 个文件,并希望将它们复制到 dir 目录中的另一个目录,该目录是我在迭代之前创建的。在代码中,我想将review
(代表第 i 个文本文件或评论)复制到trainingDir
. 我怎样才能做到这一点?似乎没有这样的功能(或者我找不到)。谢谢你。
boolean success = false;
File[] reviews = dir.listFiles();
String trainingDir = dir.getAbsolutePath() + "/trainingData";
File trDir = new File(trainingDir);
success = trDir.mkdir();
for(int i = 1; i <= 20; i++) {
File review = reviews[i];
}
回答by phatmanace
you use renameTo()– not obvious, I know ... but it's the Java equivalent of move ...
您使用renameTo()– 不明显,我知道……但它是 Java 中的 move 等价物……
回答by Michael Borgwardt
There is no file copy method in the Standard API (yet). Your options are:
标准 API 中没有文件复制方法(目前)。您的选择是:
- Write it yourself, using a FileInputStream, a FileOutputStream and a buffer to copy bytes from one to the other - or better yet, use FileChannel.transferTo()
- User Apache Commons' FileUtils
- Wait for NIO2in Java 7
- 自己编写,使用 FileInputStream、FileOutputStream 和缓冲区将字节从一个复制到另一个 - 或者更好的是,使用FileChannel.transferTo()
- 用户 Apache Commons 的FileUtils
- 在 Java 7 中等待NIO2
回答by Nate
The NIO classes make this pretty simple.
NIO 类使这变得非常简单。
回答by Janusz
If you want to copy a file and not move it you can code like this.
如果你想复制一个文件而不是移动它,你可以这样编码。
private static void copyFile(File sourceFile, File destFile)
throws IOException {
if (!sourceFile.exists()) {
return;
}
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
回答by Brian
The example below from Java Tipsis rather straight forward. I have since switched to Groovy for operations dealing with the file system - much easier and elegant. But here is the Java Tips one I used in the past. It lacks the robust exception handling that is required to make it fool-proof.
下面来自Java Tips的示例相当直接。从那以后,我切换到 Groovy 来处理文件系统的操作 - 更容易和优雅。但这是我过去使用的 Java Tips 之一。它缺乏使其万无一失所需的强大异常处理。
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
回答by Arun P Johny
For now this should solve your problem
现在这应该可以解决您的问题
File source = new File("H:\work-temp\file");
File dest = new File("H:\work-temp\file2");
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
FileUtils
class from apache commons-iolibrary, available since version 1.2.
FileUtils
来自apache commons-io库的类,从 1.2 版开始可用。
Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.
使用第三方工具而不是我们自己编写所有实用程序似乎是一个更好的主意。它可以节省时间和其他宝贵的资源。
回答by Stu Thompson
You seem to be looking for the simple solution (a good thing). I recommend using Apache Common's FileUtils.copyDirectory:
您似乎正在寻找简单的解决方案(一件好事)。我建议使用 Apache Common 的FileUtils.copyDirectory:
Copies a whole directory to a new location preserving the file dates.
This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
将整个目录复制到保留文件日期的新位置。
此方法将指定目录及其所有子目录和文件复制到指定目标。目标是目录的新位置和名称。
如果目标目录不存在,则创建它。如果目标目录确实存在,则此方法将源与目标合并,源优先。
Your code could like nice and simple like this:
您的代码可以像这样简单而简单:
File trgDir = new File("/tmp/myTarget/");
File srcDir = new File("/tmp/mySource/");
FileUtils.copyDirectory(srcDir, trgDir);
回答by Bhimesh
Use
用
org.apache.commons.io.FileUtils
org.apache.commons.io.FileUtils
It's so handy
太方便了
回答by thamizhannal
Below is Brian's modified code which copies files from source location to destination location.
下面是 Brian 修改后的代码,它将文件从源位置复制到目标位置。
public class CopyFiles {
public static void copyFiles(File sourceLocation , File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
File[] files = sourceLocation.listFiles();
for(File file:files){
InputStream in = new FileInputStream(file);
OutputStream out = new FileOutputStream(targetLocation+"/"+file.getName());
// Copy the bits from input stream to output stream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
回答by Balaswamy Vaddeman
apache commons Fileutilsis handy. you can do below activities.
apache commons Fileutils很方便。您可以进行以下活动。
copying file from one directory to another directory.
use
copyFileToDirectory(File srcFile, File destDir)
copying directory from one directory to another directory.
use
copyDirectory(File srcDir, File destDir)
copying contents of one file to another
use
static void copyFile(File srcFile, File destFile)
将文件从一个目录复制到另一个目录。
用
copyFileToDirectory(File srcFile, File destDir)
将目录从一个目录复制到另一个目录。
用
copyDirectory(File srcDir, File destDir)
将一个文件的内容复制到另一个
用
static void copyFile(File srcFile, File destFile)