我有包含图像文件网址的文本文件。
我想从其他目录复制这些文件。
此代码不起作用
File source =//
File target = //
File urls = //
Scanner scanner = new Scanner(urls);
for (File child :source.listFiles())
{
if (child.isDirectory())
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
for (File childOfchild:child.listFiles())
{
if (childOfchild.getAbsolutePath().contains(line))
FileUtils.copyFileToDirectory(childOfchild,target);
}
}
}
问题是什么?
第一个文件包含我要复制的图像的网址
\actor\0211_2233188435.jpg
\actor\0405_52447453.jpg
源位置包含 704 个子目录和 250000 个文件 例如
/media/B68E392F8E38E98F/Flickr1/Flickr/actor/0001_2124494179.jpg
最佳答案
使用递归,网上可以找到例子。 This is one of them:
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();
}
}
关于java - 复制给定 url 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15861295/