我想使用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];
}
发布于 2009-07-18 03:35:54
现在,这应该可以解决您的问题
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();
}
apache commons-io库中的FileUtils
类,从1.2版开始可用。
使用第三方工具而不是自己编写所有的实用程序似乎是一个更好的想法。它可以节省时间和其他宝贵的资源。
发布于 2009-07-18 00:03:05
下面来自Java Tips的示例相当简单。从那以后,我转而使用Groovy来处理文件系统--更简单、更优雅。但这是我过去用过的Java提示。它缺乏健壮的异常处理,这是使它变得简单可靠所必需的。
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();
}
}
发布于 2009-07-17 23:52:57
如果你想复制一个文件而不是移动它,你可以像这样编写代码。
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();
}
}
https://stackoverflow.com/questions/1146153
复制相似问题