我有包含图片文件网址的文字文件。
我想从其他目录中复制这些文件。
此代码不起作用
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个文件 for examlpe
/media/B68E392F8E38E98F/Flickr1/Flickr/actor/0001_2124494179.jpg
答案 0 :(得分:0)
使用递归,在网络中可以找到示例。 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();
}
}
答案 1 :(得分:0)
下面的代码使用顺序方法将sourceDir的整个文件结构复制到destDir。我不熟悉apache-commons
lib,所以有可能有更优雅的解决方案。
public static String getNewPath(File file,File source,File dest) throws IOException {
String filePath = file.getCanonicalPath().replaceAll(source.getCanonicalPath(), "");
return dest.getCanonicalPath()+filePath;
}
public static void main(String[] args) throws IOException {
File sourceDir = new File("./f_src");
File destDir = new File("./f_dest");
Collection<File> fs = FileUtils.listFilesAndDirs(sourceDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE);
for (File f : fs) {
if (f.exists() && f.canRead()) {
if (f.isFile()) {
FileUtils.copyFile(f, new File(getNewPath(f,sourceDir,destDir)));
}
else {
FileUtils.copyDirectory(f, new File(getNewPath(f,sourceDir,destDir)));
}
}
}
}
代码假定在根项目目录中存在两个目录,即f_src
和f_dest
。这是我f_src
的测试文件结构,数字是目录,字母是文件:
f_src
|\-1
| |\-2
| | | \-3
| | | \-a
| | \-b
| \-c
|\-4
| |\-5
| | \-d
| \-e
|\-6
|\-7
| \-f
\-g
答案 2 :(得分:0)
错误是while指令的位置
File source =//
File target = //
File urls = //
Scanner scanner = new Scanner(urls);
while (scanner.hasNextLine()) {
for (File child :source.listFiles())
{
if (child.isDirectory())
String line = scanner.nextLine();
for (File childOfchild:child.listFiles())
{
if (childOfchild.getAbsolutePath().contains(line))
FileUtils.copyFileToDirectory(childOfchild,target);
}
}
}