gpt4 book ai didi

java - 如何仅复制给定文件而不是目录中的所有文件

转载 作者:行者123 更新时间:2023-12-02 04:56:53 27 4
gpt4 key购买 nike

我正在尝试创建一个自定义文件复制器,它需要源文件夹、目标文件夹和包含一些文件名的数组列表。然后复制器复制ArrayList中的文件,结构相同。

仅当文件名与数组中的元素相同时,我才能通过复制来实现它。但它会创建所有文件夹,无论目标文件是否不存在于其中。

public static void main(String[] args) {
// TODO code application logic here
File source = new File("D:\\Documents\\A X");
File dest = new File("D:\\Documents\\A X Sample");
ArrayList<String> myFiles = new ArrayList<String>();
myFiles.add("Tohi - Rooh.mp3");
try{
copyDirectory(source, dest, myFiles);;
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}

}
public static void copyDirectory(File sourceLocation , File targetLocation, ArrayList<String> array)
throws IOException {

if (sourceLocation.isDirectory()) {
String[] children = sourceLocation.list();
for(String element : children){
if (array.contains(element)){
File fileToCopy = new File(sourceLocation, element);
//System.out.println(fileToCopy.getAbsolutePath());
targetLocation.mkdir();
}
//if (!targetLocation.exists()) {
// targetLocation.mkdir();
//}
}




for (int i=0; i<children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]), array);
}
} else {
if(array.contains(sourceLocation.getName())){
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();
//System.out.println("File copied from " + sourceLocation + " to " + targetLocation);
}
}
}

所以我希望它停止创建无用的空白文件夹,并且仅在它们包含数组中的目标文件时才创建它们。有什么想法吗?

最佳答案

您正在为 sourceLocation 的每个子级调用方法 copyDirectory。纠正它的方法(不是唯一或最好的)是将要复制的文件保存在 listsourceDiretory 中。例如:

[...]
if (sourceLocation.isDirectory()) {
String[] children = sourceLocation.list();
// List to save the name of the files you want to copy
List<String> foundFiles = new ArrayList<String>(array.size());
for(String element : children){
if (array.contains(element)){
// If the file you want to copy are in the sourceDiretory
// add its name to the list
foundFiles.add(element);
targetLocation.mkdirs();
}
}
for (String foundFile : foundFiles) {
copyDirectory(new File(sourceLocation, foundFile),
new File(targetLocation, foundFile), array);
}
}
[...]

关于java - 如何仅复制给定文件而不是目录中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28679074/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com